Marco Natale
Marco Natale

Reputation: 71

Radio Button Angular 2

I'm new in Angular 2.

I have these radio buttons:

<input type="radio" name="jobb" value="Bonds">
<input type="radio" name="jobb" value="Income">

I want to call a function on myComponent Class with something like this

<input type="radio" name="jobb" value="Bonds" (change)=doSomething()>

where

doSomething(){
 console.log(`Hello`);
}

The functions is not called. I have tried with (click) too. But it doesn't work

Upvotes: 0

Views: 3183

Answers (3)

Sravan Dudyalu
Sravan Dudyalu

Reputation: 185

change the event from (change) to (click) and include the function in double quotes "dosomething()" like below code

pass a value of radio button to differentiate from one radiobutton with another in the function like "dosomething('Bonds')"

like below code

<input type="radio" name="jobb" value="Bonds" (click)="doSomething('Bonds')">
<input type="radio" name="jobb" value="Income" (click)="doSomething('Income')">

write the function in the component class

doSomething(value:string):void {
  alert(value);
}

I think this should work

Upvotes: 1

dkiriakakis
dkiriakakis

Reputation: 148

You are probably missing the double quotes.

(change)=doSomething() should be (change)="doSomething()"

Have a look at the following plunkr in src/test-item-radio.ts:

@Component({
selector: 'test-item-radio',
template: `
  <div>
    Answer: {{ answer }}
  </div>
  <div class="radio" *ng-for="#option of itemData">
        <label>{{option.id}}
            <input type="radio" [value]="option.id"
                   (change)="doSomething()" name="radio-list" [checked]='answer==option.id'>
            <span>{{ option.name }}</span>
        </label>
    </div>
`,
directives: [FORM_DIRECTIVES, NgFor],
providers: []
})
export class TestItemRadio {

@Input()
itemData;

answer: string;

constructor() {
  console.log(this.itemData);
  this.answer=2;
}

doSomething() {
  alert('hello');
}
}

http://plnkr.co/edit/F4ukpS2lExNJvb1CYwbF?p=info

Upvotes: 2

ranakrunal9
ranakrunal9

Reputation: 13558

You can get radio value by passing $event.target.value as argument for doSomething function as below :

<input type="radio" name="jobb" value="Bonds" (change)="doSomething($event.target.value)">Bonds
<input type="radio" name="jobb" value="Income" (change)="doSomething($event.target.value)">Income

function in Component :

doSomething(data: any){
  console.log('Hello ' + data);
}

You can check Plunker at : https://plnkr.co/edit/MqUD0fGCUcF7brMEx1rq

Upvotes: 0

Related Questions