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

javascript - Reading radio button value - Angular 2 - Stack Overflow

programmeradmin3浏览0评论

I'm trying to read the radio button value - in angular 2,

index.html

<input type="radio" id="options1" name="function" value="create">
<input type="radio" id="options2" name="function" value="continue">

index.ts

@Component({
    selector: 'function',
    templateUrl: './client/ponents/function/index.html',
    styleUrls: ['./client/ponents/function/index.css'],
    providers: [],
    directives: [ROUTER_DIRECTIVES]
})

I need to display a div in the html based on if radio button value is create or continue.

What I've tried:

  1. Fetching values of radio button in the typescript file using document.getElementById - Property checked wasn't getting detected.
  2. Reading the value using model.function by defining a model in the typescript. Unable to access the model variable, obviously!
  3. Tried using [(ngModel)] - that didn't work either.

Please suggest a turnaround for this.

I'm trying to read the radio button value - in angular 2,

index.html

<input type="radio" id="options1" name="function" value="create">
<input type="radio" id="options2" name="function" value="continue">

index.ts

@Component({
    selector: 'function',
    templateUrl: './client/ponents/function/index.html',
    styleUrls: ['./client/ponents/function/index.css'],
    providers: [],
    directives: [ROUTER_DIRECTIVES]
})

I need to display a div in the html based on if radio button value is create or continue.

What I've tried:

  1. Fetching values of radio button in the typescript file using document.getElementById - Property checked wasn't getting detected.
  2. Reading the value using model.function by defining a model in the typescript. Unable to access the model variable, obviously!
  3. Tried using [(ngModel)] - that didn't work either.

Please suggest a turnaround for this.

Share Improve this question edited Sep 19, 2016 at 18:02 Matthew Green 10.4k4 gold badges39 silver badges55 bronze badges asked Sep 19, 2016 at 17:55 Ramana SarvaRamana Sarva 2932 gold badges5 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

template:

<input type="radio" id="options1" [(ngModel)]="myRadio" value="create">
<input type="radio" id="options2" [(ngModel)]="myRadio" value="continue">

then define a myRadio variable in your ponent and initialize it like this: myRadio: string = ''

this variable will get the chosen value.

and, do not use javascript to control DOM elements in Angular2, this is against the angular2 philosophy

If you only have 2 or 3 radio options, your easiest choice is to use template reference variable, as shown below:

<input #op1 type="radio" id="options1" name="function" value="create">
<input #op2 type="radio" id="options2" name="function" value="continue">

<button (click)="fn(op1.checked ? op1.value : op2.checked ? op2.value)">Run</button>
发布评论

评论列表(0)

  1. 暂无评论