简体   繁体   中英

Angular template reference variable for radio buttons

I know about this:

<input type="text" #inp>
<button type="button" (click)="onClick(inp.value)">Click</button>

So I get the value I typed into textbox without having to use ngModel directive.

Is there any similar approach to work with radio buttons without having to use ngModel?

<input type="radio" value="selected" name="viewType">Selected
<input type="radio" value="unselected" name="viewType">Unselected
<input type="radio" value="both" name="viewType">Both

Below these radio buttons I have a refresh button like this:

<button (click)="refreshView()">Refresh</button>

These html input elements aren't part of any form tag. What I want is to have a "refreshView" function call with a parameter - the selected radio button value.

Is this possible?

If you have only a few radio buttons, the following syntax would work. It gets the value associated with the radio button that is checked, with the help of nested conditional operators .

<input #rad1 type="radio" value="selected" name="viewType" >Selected
<input #rad2 type="radio" value="unselected" name="viewType" >Unselected
<input #rad3 type="radio" value="both" name="viewType" >Both

<button (click)="refreshView(rad1.checked ? rad1.value : rad2.checked ? rad2.value : rad3.checked ? rad3.value : null)">Refresh</button>

See this stackblitz for a demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM