首页 > 解决方案 > 使用ngfor向模板动态添加复选框时如何显示其他文本区域

问题描述

我目前正在使用 ngFor 来生成复选框 HTML。但是,当使用此方法时,我无法将特定的模板引用变量分配给另一个复选框,只是为了显示/隐藏基于复选框是否选中的文本区域。

我试图通过数据数组分配一个模板引用变量,但这似乎不起作用。我还尝试在页面上手动创建复选框,然后允许我添加模板引用变量,但是一旦完成,我似乎没有从复选框中获取所需的值。

<ul formArrayName="health_care_goals">
    <li  class="form-group" *ngFor="let goal of health_care_goals; let i = index" formGroupName="{{i}}">
        <input id="{{goal.id}}" type="checkbox" formControlName="{{goal.id}}">
        <label for="{{goal.id}}"><span></span>{{goal.name == 'Other' ? 'Other (Provide details here)' : goal.name}}</label>
    </li>
</ul>
<textarea *ngIf="health_care_goals_other" formControlName="health_care_goals_response_other"></textarea>
for (let i = 0; i < this.health_care_goals.length; i++) {
            let fg = new FormGroup({});
            fg.addControl(this.health_care_goals[i].id, new FormControl('', Validators.required));
            all_health_care_goals.push(fg);
}

this.goalsForm = this._formBuilder.group({
            health_care_goals: all_health_care_goals,
            health_care_goals_response_other: [''],
            medication_goal_reduce_harm: medication_goal_reduce_harm_strategies,
            reduce_harm_from_effects_of_med: [''],
            reduce_harm_from_effects_of_med_text: [''],
            reducing_harms_other: ['']
});

    private health_care_goals = [
        {name: 'Prolonging life', id: 'prolonging_life'},
        {name: 'Optimising functional independence', id: 'optimising_functional_independence'},
        {name: 'Optimising quality of life', id: 'optimising_quality_of_life'},
        {name: 'Achieving a peaceful death', id: 'achieving_a_peaceful_death'},
        {name: 'Symptom control', id: 'symptom_control'},
        {name: 'Maintaining good health and preventing illness', id: 'maintaining_good_health_and_preventing_illness'},
        {name: 'Other', id: 'other'}
    ];

我只想在选中另一个复选框时显示文本区域。

标签: angularangular4-forms

解决方案


您必须在整个 div 上重复并为每个复选框提供条件

<div fxFlex *ngFor="let item of items" fxLayout="row">
   <mat-checkbox value="item.value" (change)="decideToShow(item)"></mat-checkbox>
   <textarea type="text" *ngif="item.showDesc" [(ngModel)]="item.description"></textarea>
</div>

并在您的 ts 中定义一个函数decideToShow(item)

decideToShow(item): void {
    if(item.value && index > 3){
        item.showDesc = true;
    } else {
        item.showDesc = false;
    }
}

推荐阅读