我建议用于填充其他值的
<input>
元素不要使用 formControlName
指令。
当输入文本字段时,它应该更新
favFruit
控制值,这会导致取消选中之前选中的单选按钮。
<input type="text" value="" id="favFruit" name="favFruit" #otherFavFruit
(input)="onOtherFavFruitInput(otherFavFruit.value)">
onOtherFavFruitInput(value: string) {
this.form.controls.favFruit.setValue(value);
}
另一种情况是,当您在文本字段中输入其他值时,您改变主意并选择其中一个单选按钮,您可以使用
(change)
事件来重置输入字段。
<input type="radio" value="Apple" id="favFruit" name="favFruit" formControlName="favFruit"
(change)="onFavFruitChecked($event)">
import { Component, ElementRef, ViewChild } from '@angular/core';
@ViewChild('otherFavFruit') otherFavFruit!: ElementRef<HTMLInputElement>;
onFavFruitChecked(event: any) {
this.otherFavFruit.nativeElement.value = '';
}
请注意,您可以使用
*ngFor
生成一组表单控件,旨在减少 HTML 中的代码。
<ng-container *ngFor="let fruit of fruits">
<input type="radio" [value]="fruit" id="favFruit" name="favFruit" formControlName="favFruit"
(change)="onFavFruitChecked($event)"> {{ fruit }}
<br>
</ng-container>
fruits = ['Apple', 'Banana', 'Orange', 'Pear', 'Grapes'];