如何以编程方式动态创建angular2中的多个独立组件实例?

Rol*_*ndo 8 angular

我有一个按钮组件fancy-textbox.我想让用户可以动态添加新的fancy-textbox,但是它们在文本框上面有不同的标签,这些标签基于对fancy-textbox自身唯一的范围变量(或者可能来自不在所有范围内共享的父范围变量fancy-textboxes).我该怎么做呢?目前,我直接在我的模板显示和隐藏中使用它,但我希望能够以编程方式"动态添加更多此实例":

<div *ngIf="showTextBox">
    <fancy-textbox labelForBox="TextBox 1"></fancy-textbox>  
</div>
Run Code Online (Sandbox Code Playgroud)

如果仅在一个特定区域的DOM中创建花式文本框,那就很好.但是,我想要做的是能够在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>
Run Code Online (Sandbox Code Playgroud)

鉴于上面的模板...假设用户在文本框中输入了类名(例如botsection)并点击"createfancybutton"按钮,我希望将""" <fancy-button></fancy-button>"放入页面的相应部分,我希望能够在页面模板的不同部分内动态"创建"独立"花式按钮"的实例.我可以用ng-for粘贴3 ng-if语句,虽然看起来不切实际.寻找更好的替代方案......

更新:所以步骤将是:

1)用户在文本框中输入"midsection".2)用户点击"创建花式按钮"按钮3) - <fancybutton></fancybutton>组件将被添加到div的下面,类名为"midsection" -

用户可以重复单击相同的"创建花式按钮"按钮以在此下创建更多.如果用户将输入框更改为"topsection",那么当用户单击"创建花式按钮"时,fancybutton组件将添加到带有"topsection"的div下.

如果用户输入"newsection",那么将在div下使用类名"container"创建一个类名为"newsection"的新div,并将fancybutton组件添加到具有classname"newsection"的div中.

JB *_*zet 1

您的组件中有一系列标签。

使用 *ngFor 迭代此数组并为每个标签生成一个精美的文本框。

要添加新的精美文本框,请向数组添加新标签。

<fancy-textbox *ngFor="let label of labels" [labelForBox]="label"></fancy-textbox>  
Run Code Online (Sandbox Code Playgroud)

并在组件中:

labels: string[] = [];

// to add a fancy textbox:
this.labels.push('new label');
Run Code Online (Sandbox Code Playgroud)