gpt4 book ai didi

javascript - 在单选按钮组内输入文本字段

转载 作者:行者123 更新时间:2023-11-30 20:41:57 25 4
gpt4 key购买 nike

有没有办法将 ngModel 绑定(bind)到 radio group 内的 input 文本字段?我有一个多选单选按钮组,最后一个选项是 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 的值没有将其自身绑定(bind)到单选按钮的值。这就是为什么每次输入文本更改时 radio 都会取消选中。有什么办法可以实现这个要求吗?

最佳答案

This stackblitz 展示了一种方法。使用了两个属性:goalOption 绑定(bind)到选定的单选按钮值,customGoalName 绑定(bind)到输入文本。当两者中的任何一个发生变化时,通过在属性 setter 中调用 updateGoalName 来更新 goal.name

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>

关于javascript - 在单选按钮组内输入文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49164751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com