angular - 使用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'}
];
我只想在选中另一个复选框时显示文本区域。
解决方案
您必须在整个 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;
}
}
推荐阅读
- python - 如何停止线程并重新启动它 - python
- python - 如何使用 RMSE 作为我的时间序列拆分网格搜索的评分指标?
- vue.js - 带有多个激活器的 Vuetify 对话框
- selenium - E2E 测试对确切测试的内容有点困惑
- r - 从原始数据创建数据组并绘制它?
- javascript - 使用 JS 从任何元素中获取所有样式
- python - 使用 Pytorch 处理非 NLP 任务的多任务 LSTM
- nginx - NGINX 通过 HTTPS 反向代理到 Nuxt 应用程序
- python - 如何在 keras 中获取输入并行层
- swiftui - 如何充分利用小部件内存限制和每天的刷新次数