最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular template reference variable for radio buttons - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Feb 24, 2019 at 20:37 robertrobert 6,1527 gold badges31 silver badges40 bronze badges 2
  • It can probably be done but it would be easier with ngModel. Is there a reason for not using it? – Martin Parenteau Commented Feb 24, 2019 at 21:28
  • Just to avoid creating an extra variable simply to hold the viewType which is not used anywhere else. "refreshView" function could do all the setup if it can get the correct viewType from the template. – robert Commented Feb 24, 2019 at 21:35
Add a ment  | 

1 Answer 1

Reset to default 10

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.

发布评论

评论列表(0)

  1. 暂无评论