首页 > 解决方案 > Angular 6 - 选择名称时显示动态div

问题描述

我有一个数组,数组内容显示为员工姓名的复选框列表。我想,当我选择一个复选框(选择员工姓名)时,它将显示一个 DIV,其中包含所选员工姓名和相关员工的文本区域(用于评论)。该 DIV 将为列表中的每个选定名称动态显示。请指导我如何达到所需的结果。

标签: angular

解决方案


我会这样做:

在您的 component.ts 中:

selectedEmployees: string[];

toggleEmployee(empl: string): void {
    const index = this.selectedEmployees.indexOf(empl)
    if(index > -1) {
        this.selectedEmployees.push(empl);
    } else {
        this.selectedEmployees.splice(index, 1);
    }       
}

在您的 html 中:

<input type="checkbox" (click)="toggleEmployees('James')" value="James">
<input type="checkbox" (click)="toggleEmployees('Charles')" value="Charles">

<div *ngIf="let empl of selectedEmployees">
   {{ empl }}
<div>

我希望这回答了你的问题


推荐阅读