使用 Angular,如何在单击时动态添加组件? (不止一个)

Using Angular, how Can I add dynamically a component on click ? (Not only one)

要学习 Angular 我正在编写一个 to-do 列表。 我创建了一个带有标题(任务名称)和状态(与复选框输入相关的布尔值)参数的组件任务。

<div>
  <div>{{title}} <button>Edit</button></div>
  <input type="checkbox" value={{status}}>
</div>

我还创建了一个 ToDoList 组件,其中包含一个标题(to-do 列表的名称,以及一个带有任务名称列表的选项卡,用于使用 *ngFor.

<div>
  <h1>{{title}}</h1>
  <app-task *ngFor="let title of list" [title]="title" status="true"></app-task>
  <button (click)="appTaskDirective">Add a task</button>
</div>

现在我想在使用 appTaskDirective 时通过单击 "Add a task button" 来动态添加任务组件,但我就是想不通。

angulardocument example帮不上忙

这是我的 appTaskDirective 文件:

import { Directive, ViewContainerRef, TemplateRef, OnInit } from '@angular/core';

@Directive({
  selector: '[appTaskDirective]'
})

export class TaskDirectiveDirective implements OnInit {
  constructor(public viewContainer:ViewContainerRef) { }
}

谢谢。

首先,您不能将指令传递给点击事件。 如果你想使用指令来监听点击事件,你必须像这样将一个主机监听器附加到指令

在指令中

import { Directive, ViewContainerRef, TemplateRef, OnInitHostListener } from '@angular/core';

@Directive({
  selector: '[appTaskDirective]'
})

export class TaskDirectiveDirective implements OnInit {
  constructor(public viewContainer:ViewContainerRef) { }
    @HostListener('click') onClick() {
     // do something
    }
}

组件中

<div>
  <h1>{{title}}</h1>
  <app-task *ngFor="let title of list" [title]="title" status="true"></app-task>
  <button appTaskDirective>Add a task</button>
</div>

但我不明白为什么你需要做所有这些。您可以只监听组件中的事件并相应地更新任务列表

在组件中 html

<div>
 <h1>{{title}}</h1>
 <app-task *ngFor="let title of list" [title]="title" status="true"></app-task>
 <button (click)="addNewTask()">Add a task</button>
</div>

在组件 ts

addNewTask() {
   this.list.push('A new Task');
}

希望这对您有所帮助:)