有没有办法将ngModel
绑定到input
内的radio group
文本字段?我有一个多选单选按钮组,最后一个选项为other
(带输入文本)。以下是我到目前为止的情况:
<mat-radio-group fxLayout="column" name="goal_name" [(ngModel)]="goal.name">
<mat-radio-button *ngFor="let gn of goalNames" name="goal_name" [value]="gn">{{gn}}</mat-radio-button>
<mat-radio-button value="" name="goal_name">
<mat-form-field>
<input matInput placeholder="Other" [(ngModel)]="goal.name" name="something">
</mat-form-field>
</mat-radio-button>
</mat-radio-group>
goalNames = ["buy", "travel", "save",
"build", "retire"];
此实现的问题是ngmodel
的值不会将其自身绑定到单选按钮的值。这就是为什么,每当输入文本改变时,无线电都会取消选中。有没有办法实现这个要求?
答案 0 :(得分:1)
This stackblitz 显示了一种方法。使用了两个属性:goalOption
绑定到选定的单选按钮值,customGoalName
绑定到输入文本。如果更改了其中任何一个,则通过在属性设置器中调用goal.name
来更新updateGoalName
。
private _goalOption: string = "";
private _customGoalName: string = "";
goal = { name: "" };
goalNames = ["buy", "travel", "save", "build", "retire"];
get goalOption(): string {
return this._goalOption;
}
set goalOption(value: string) {
this._goalOption = value;
this.updateGoalName();
}
get customGoalName(): string {
return this._customGoalName;
}
set customGoalName(value: string) {
this._customGoalName = value;
this.updateGoalName();
}
private updateGoalName(): void {
this.goal.name = this._goalOption === "other" ? this._customGoalName : this._goalOption;
}
自定义目标名称的单选按钮在模板中的值为other
。输入事件ngModelChange
的处理程序确保在用户键入自定义目标名称时选中other
单选按钮。
<mat-radio-group fxLayout="column" name="goal_name" [(ngModel)]="goalOption">
<mat-radio-button *ngFor="let gn of goalNames" name="goal_name" [value]="gn">{{gn}}</mat-radio-button>
<mat-radio-button value="other" name="goal_name">
<mat-form-field>
<input matInput placeholder="Other" [(ngModel)]="customGoalName" (ngModelChange)="goalOption = 'other'" name="something">
</mat-form-field>
</mat-radio-button>
</mat-radio-group>