Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 281
robert Avatar asked Feb 24 '19 20:02

robert


People also ask

What is template reference variable in Angular?

Template Reference Variable in angular is used to access all the properties of any element inside DOM. It can also be a reference to an Angular component or directive or a web component. Template Reference Variable can refer to the following – DOM element. Directives.

How do I pass a template reference variable in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .

Are radio buttons Boolean values?

Radio Button do not work for bool value.


1 Answers

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.

like image 160
ConnorsFan Avatar answered Oct 10 '22 02:10

ConnorsFan