Search code examples
typescriptangular9angular12

How to trigger radio button in angular 12


I am trying to trigger the radio button in angular 12 but it is not working. If i click the button depends on the text i want to checked the radio button.

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>

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


Solution

  • In your current code, your texts just come after the input, but there is nothing that defines that a text really belong to its corresponding input. An easy way to fix this is to declare your texts (Beef, Lamb, Fish) as label for their input. Just add a label and reference the id of each input with the forattribute.

    <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>
    

    In order to trigger the radio buttons via normal buttons, you can just set your ngModel to the corresponding value inside your checkit() function like that:

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

    Try it out in this StackBlitz.