【问题标题】:Using Angular, how Can I add dynamically a component on click ? (Not only one)使用 Angular,如何在点击时动态添加组件? (不止一个)
【发布时间】:2019-09-03 06:02:11
【问题描述】:

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

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

我还创建了一个 ToDoList 组件,其中包含一个标题(待办事项列表的名称,以及一个带有任务名称列表的选项卡,以使用 *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时点击“添加任务按钮”动态添加任务组件,但我就是想不通。

棱角分明的document example 帮不上忙。

这是我的appTaskDirective 文件:

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

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

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

谢谢。

【问题讨论】:

标签: angular dynamic components directive


【解决方案1】:

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

在指令中

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');
}

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多