Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically dynamically create multiple independent instances of component in angular2?

Tags:

angular

I have a button component fancy-textbox. I want to make it such that users can dynamically add new fancy-textbox, but they have different labels above the textbox that is based on a scope variable that is unique to the fancy-textbox itself (or maybe from a parent scope variable that is not shared among all fancy-textboxes). How do I do this? Currently, I use this directly in my template showing and hiding, but I want to be able to "dynamically add more instances of this" programatically:

<div *ngIf="showTextBox">
    <fancy-textbox labelForBox="TextBox 1"></fancy-textbox>  
</div>

That is good, if fancy-textboxes are only created in the DOM in one specific area. However, what I want to do, is to be able to dynamically create components in different sections of the DOM.

    <div class="container">
<div class="navsection"><input id="classname" type="text"><button (click)="createFancyButton()">Create Fancy Button</button></div>
    <div class="topsection">
    </div>
    <div class="midsection">
    </div>
    <div class="botsection">
    </div>
<div class="footsection"></div></div>

Given the template above... assuming that users input the classname (e.g. botsection) into the textbox and hit the "createfancybutton button), I want "" "<fancy-button></fancy-button>" to be put into the appropriate section of the page, I want to be able to dynamically "create" instances of independent "fancy-button" within different sections of the page template. I could stick 3 ng-if statements with ng-for, though it seems impractical. Looking for a better alternative...

UPDATE: So the steps would be:

1) User enters "midsection" into textbox. 2) User clicks on the button "Create Fancy Button" 3) - The <fancybutton></fancybutton> component would be added under the div with the classname "midsection"-

The user can repeat clicking on the same "Create Fancy Button" button to create more under that. If user changes the input box to "topsection", then when user clicks on "Create Fancy Button", the fancybutton component would be added under div with "topsection".

If the user enters "newsection", then a new div with classname "newsection" would be created under the div with the classname "container", and fancybutton component would be added to the div with classname "newsection".

like image 586
Rolando Avatar asked Oct 30 '16 05:10

Rolando


1 Answers

Have an array of labels in your component.

Use *ngFor to iterate over this array and generate a fancy textbox for each of those labels.

To add a new fancy-textbox, add a new label to the array.

<fancy-textbox *ngFor="let label of labels" [labelForBox]="label"></fancy-textbox>  

And in the component:

labels: string[] = [];

// to add a fancy textbox:
this.labels.push('new label');
like image 76
JB Nizet Avatar answered Oct 01 '22 11:10

JB Nizet