我有一个 Angular (v2.4.8) 形式,它在基于 scotch.io 中的示例的单选选择中使用 ngFor 。这在我的应用程序中不起作用,如果我单击单选按钮,user.category
不会更新。
组件代码:
export class RegistrationComponent implements OnInit {
public user: User;
public userTypes = [
{value: 'type1', display: 'Type 1'},
{value: 'type2', display: 'Type 2'},
{value: 'type3', display: 'Type 3'}
];
constructor() { }
ngOnInit() {
this.user = {
name: '',
email: '',
category: this.userTypes[0].value
}
}
public save(isValid: boolean, f: User) {
console.log(f);
}
}
模板:
<div class="btn-group" data-toggle="buttons">
<label *ngFor="let userType of userTypes" class="btn btn-outline-secondary">
<input type="radio" name="category" [(ngModel)]="user.category" [value]="userType.value"> {{userType.display}}
</label>
</div>
用户界面如下:
export interface User {
name: string;
email: string;
category: string;
}
编辑
这似乎是使用 bootstrap btn-group
和 Angular 时出现的问题,看起来我正确处理了点击事件。我通过向标签添加单击事件来修复它。回答如下。
最佳答案
这是 Bootstrap btn-group radio 的问题,而不是 Angular 问题。解决方法是向标签添加点击事件。
HTML:
<label *ngFor="let userType of userTypes" class="btn btn-outline-secondary" (click)="changeCategory(userType.value)">
<input type="radio" name="category" [(ngModel)]="user.category" [value]="userType.value"> {{userType.display}}
</label>
Javascript - 添加到组件:
public changeCategory(category) {
this.user.category = category;
}
关于javascript - Angular radio 输入未使用 bootstrap 4 btn-group 更新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42766414/