如何在angular12中触发单选按钮

How to trigger radio button in angular 12

我正在尝试触发 angular 12 中的单选按钮,但它不起作用。如果我点击按钮取决于我想检查单选按钮的文本。

If i click beef button, beef radio button should be checked. 
If i click Lamb button, Lamb radio button should be checked. 
If i click Fish button, Fish radio button should be checked.

radios.component.html:

<input type="radio" name="food" value="beef" [(ngModel)]="myFood" /> Beef
<input type="radio" name="food" value="lamb" [(ngModel)]="myFood" /> Lamb
<input type="radio" name="food" value="fish" [(ngModel)]="myFood" /> Fish

<br /><br />

<button (click)="checkit('beef')">Beef</button>
<button (click)="checkit('lamb')">Lamb</button>
<button (click)="checkit('fish')">Fish</button>

演示:https://stackblitz.com/edit/angular-ivy-rktjxe?file=src%2Fapp%2Fradios%2Fradios.component.html

在您当前的代码中,您的文本只是在输入之后出现,但没有任何内容可以定义文本确实 属于 对应的输入。解决此问题的一个简单方法是将您的文本(牛肉、羊肉、鱼)声明为其输入的标签。只需添加一个标签并使用 for 属性引用每个输入的 id

<input type="radio" id="beef" name="beef" value="beef" [(ngModel)]="myFood">
<label for="beef">Beef</label>

<input type="radio" id="lamb" name="lamb" value="lamb" [(ngModel)]="myFood">
<label for="lamb">Lamb</label>

<input type="radio" id="fish" name="fish" value="fish" [(ngModel)]="myFood">
<label for="fish">Fish</label>

为了通过普通按钮触发单选按钮,您只需将 ngModel 设置为 checkit() 函数中的相应值,如下所示:

checkit(val: string) {
    this.myFood = val;
}

this StackBlitz 中试用。