Angular 5 - 点击事件将组件添加到 DIV 中

3

我正在使用Angular 5,有如下代码:

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  appendToContainer() {
    // Do the stuff here
    // Append PanelComponent into div#container
  }

}

现在是 app.component.html。
// app.component.html
<button (click)="appendToContainer()"></button>
<div id="container"></div>

最后,我有一个简单的组件。
// panel.component.html
<div class="panelComponent">
  This is a panel Component html
</div>

每次单击app.component.html上的按钮,我想要实现的是将panel.component附加到app.component.html中。如何做到这一点?

我有一种感觉,你从错误的角度来看待这个问题。难道你不应该使用 *ngFor 迭代一个数组吗? - Deblaton Jean-Philippe
你可以使用一个对象数组,在调用 appendToContainer 时将其附加到数组中,并使用 *ngFor 为数组中的每个项目创建一个面板。 - FabioG
当按钮被点击时,我想要做的是在组件上创建一个新实例并将其附加在 div 内部。 - user8770372
@pedromartinez 你找到任何解决方案了吗? - Md. Mahmud Hasan
1个回答

1
你可以使用 *ngFor 和一个变量来实现你想要的效果。
//In your component
num:number=0

//You html like 
<button (click)="num++"></button>
//we create a array "on fly" and slice to get only a "num" items
<div *ngFor="let item in [0,1,2,3,4,5,6,7,8,9].slice(0,num)" class="panelComponent">
  This is a panel Component html
</div>

当按钮被点击时,我想要做的是在组件上创建一个新实例并将其附加在 div 内部。 - user8770372
1
也许你会喜欢 https://blog.dmbcllc.com/dynamically-add-components-in-angular/ ? - Eliseo
似乎那段代码不适用于Angular 5。这是我的app.component.ts文件:import { Component } from '@angular/core'; import { ChildComponent } from './child/child.component';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { constructor() {} addCmp() { console.log('adding'); // 添加一个ChildComponent实例 } } - user8770372

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接