Reading radio button value - Angular 2

19,186

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

Share:
19,186
Ramana Sarva
Author by

Ramana Sarva

Still searching for the rabbit. Still waiting for that line - 'Wake up, Neo'.

Updated on June 29, 2022

Comments

  • Ramana Sarva
    Ramana Sarva almost 2 years

    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/components/function/index.html',
        styleUrls: ['./client/components/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.