首页 > 解决方案 > 绑定到 *ngFor 内部的属性

问题描述

我有一个简单的表格循环,但我无法获得选定的单选按钮来更新属性。我写了这个 HTML:

<tr *ngFor="let question of questionsFor(category)">
    <td>{{ question.question }}</td>
    <td>
        <input type="radio" value="1" name="{{ question.id }}" [ngModel]="question.pass">Pass
        <input type="radio" value="0" name="{{ question.id }}" [ngModel]="question.pass">Fail
    </td>
</tr>

当我点击提交按钮并查看pass问题数组中的属性时,它们都设置为undefined.

问题数组只是一个简单的类。

export class SmbwaQuestion {
    id: number;
    question: string;
    pass: number;
}

标签: angularangular5

解决方案


要触发双向绑定,您应该使用[(ngModel)]符号,否则父组件中的值不会更新

<input type="radio" value="1" name="{{ question.id }}" [(ngModel)]="question.pass">Pass
<input type="radio" value="0" name="{{ question.id }}" [(ngModel)]="question.pass">Fail

推荐阅读