Angular2 - binding radio buttons

I want to use a radio button in a form using Angular 2

Options : <br/> 1 : <input name="options" ng-control="options" type="radio" value="1" [(ng-model)]="model.options" ><br/> 2 : <input name="options" ng-control="options" type="radio" value="2" [(ng-model)]="model.options" ><br/> 
Initial value

model.options is 1

when the page is loaded, the first radio button is unchecked and the changes are not tied to the model

Any idea?

+120
radio-button angular forms
Aug 07 '15 at 13:56 on
source share
11 answers

use [value] = "1" instead of value = "1"

 <input name="options" ng-control="options" type="radio" [value]="1" [(ngModel)]="model.options" ><br/> <input name="options" ng-control="options" type="radio" [value]="2" [(ngModel)]="model.options" ><br/> 

Edit:

As suggested by thllbrg "For angular 2.1+ use [(ngModel)] instead of [(ng-model)] "

+104
Aug 6 '16 at 11:44
source share

Note. Now binding the snap switch is supported in RC4 - see this answer

An example of a Radio button using the RadioControlValueAccessor user parameter, similar to the CheckboxControlValueAccessor flag ( Updated with Angular 2 rc-1 )

App.ts

 import {Component} from "@angular/core"; import {FORM_DIRECTIVES} from "@angular/common"; import {RadioControlValueAccessor} from "./radio_value_accessor"; import {bootstrap} from '@angular/platform-browser-dynamic'; @Component({ selector: "my-app", templateUrl: "template.html", directives: [FORM_DIRECTIVES, RadioControlValueAccessor] }) export class App { model; constructor() { this.model = { sex: "female" }; } } 

template.html

 <div> <form action=""> <input type="radio" [(ngModel)]="model.sex" name="sex" value="male">Male<br> <input type="radio" [(ngModel)]="model.sex" name="sex" value="female">Female </form> <input type="button" value="select male" (click)="model.sex='male'"> <input type="button" value="select female" (click)="model.sex='female'"> <div>Selected Radio: {{model.sex}}</div> </div> 

radio_value_accessor.ts

 import {Directive, Renderer, ElementRef, forwardRef} from '@angular/core'; import {NG_VALUE_ACCESSOR, ControlValueAccessor} from '@angular/common'; export const RADIO_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RadioControlValueAccessor), multi: true }; @Directive({ selector: 'input[type=radio][ngControl],input[type=radio][ngFormControl],input[type=radio][ngModel]', host: {'(change)': 'onChange($event.target.value)', '(blur)': 'onTouched()'}, bindings: [RADIO_VALUE_ACCESSOR] }) export class RadioControlValueAccessor implements ControlValueAccessor { onChange = (_) => {}; onTouched = () => {}; constructor(private _renderer: Renderer, private _elementRef: ElementRef) {} writeValue(value: any): void { this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value == this._elementRef.nativeElement.value); } registerOnChange(fn: (_: any) => {}): void { this.onChange = fn; } registerOnTouched(fn: () => {}): void { this.onTouched = fn; } } 

Source: https://github.com/angular2-school/angular2-radio-button

Plunker demo: http://plnkr.co/edit/aggee6An1iHfwsqGoE3q?p=preview

+61
Jan 08 '16 at 12:45
source share

My manual workaround, which includes manually updating model.options when selecting a new radio button:

 template: ` <label *ngFor="let item of radioItems"> <input type="radio" name="options" (click)="model.options = item" [checked]="item === model.options"> {{item}} </label>` class App { radioItems = 'one two three'.split(' '); model = { options: 'two' }; } 

This Plunker demonstrates the above, as well as how to use the button to change the selected switch - that is, to prove that the data binding is two-way:

 <button (click)="model.options = 'one'">set one</button> 
+43
Dec 03 '15 at 4:59
source share

Here is the best way to use radio buttons in Angular2. There is no need to use the (click) event or RadioControlValueAccessor to change the value of the binding property, and the [checked] property does the trick.

 <input name="options" type="radio" [(ngModel)]="model.options" [value]="1" [checked]="model.options==1" /><br/> <input name="options" type="radio" [(ngModel)]="model.options" [value]="2" [checked]="model.options==2" /><br/> 

I published an example of using switches: Angular 2: how to create switches from an enumeration and add two-way binding? It works with at least Angular 2 RC5.

+36
Sep 09 '16 at 8:33
source share

This problem is solved in version Angular 2.0.0-rc.4 respectively in forms.

Include "@angular/forms": "0.2.0" in package.json.

Then expand your boot file in the main window. Relevant Part:

 ... import { AppComponent } from './app/app.component'; import { disableDeprecatedForms, provideForms } from '@angular/forms'; bootstrap(AppComponent, [ disableDeprecatedForms(), provideForms(), appRouterProviders ]); 

I have it in .html and it works fine: value: {{buildTool}}

 <form action=""> <input type="radio" [(ngModel)]="buildTool" name="buildTool" value="gradle">Gradle <br> <input type="radio" [(ngModel)]="buildTool" name="buildTool" value="maven">Maven </form> 
+18
Jul 20 '16 at 14:14
source share

I was looking for the right method to handle these radio buttons, here is an example of the solution I found here:

 <tr *ngFor="let entry of entries"> <td>{{ entry.description }}</td> <td> <input type="radio" name="radiogroup" [value]="entry.id" (change)="onSelectionChange(entry)"> </td> </tr> 

Notice the onSelectionChange , which passes the current element to the method.

+6
Feb 14 '17 at 5:01
source share

Radio input is not yet supported. There should be an accessory for entering the radio input (similar to the one flag, where it sets the 'checked' attr here ), but I did not find it. Therefore, I implemented one; You can check it out here .

+4
Aug 09 '15 at 10:12
source share

[value] = "item" using * ngFor also works with reactive forms in Angular 2 and 4

 <label *ngFor="let item of items"> <input type="radio" formControlName="options" [value]="item"> {{item}} </label>` 
+4
May 23 '17 at 17:54
source share

The simplest solution and workaround:

 <input name="toRent" type="radio" (click)="setToRentControl(false)"> <input name="toRent" type="radio" (click)="setToRentControl(true)"> setToRentControl(value){ this.vm.toRent.updateValue(value); alert(value); //true/false } 
+1
Jan 06 '16 at 11:10
source share

I created the version using only the click event for the loaded elements and passing the selection value to the "getSelection" function and updating the model.

In your template:

 <ul> <li *ngFor="let p of price"><input type="radio" name="price" (click)="getValue(price.value)" value="{{p}}" #price> {{p}} </li> </ul> 

Your class:

 export class App { price:string; price = ["1000", "2000", "3000"]; constructor() { } model = new SomeData(this.price); getValue(price){ this.model.price = price; } } 

See an example: https://plnkr.co/edit/2Muje8yvWZVL9OXqG0pW?p=info

+1
Jun 21 '16 at 4:00
source share

This may not be the right decision, but it is an option that might help someone.

So far, I have been getting the radioButtons value using the (click) method, for example:

 <input type="radio" name="options" #male (click)="onChange(male.value)">Male <input type="radio" name="options" #female (click)="onChange(female.value)">Female 

and in the .ts file, I set the value of the predefined variable to the getter value of the onChange function.

But after searching, I found a good method, I have not tried it yet, but it seems that it’s good using the link [(ng-model)] here to github here . it uses RadioControlValueAccessor for radio as well as for checkbox. # plnkr # works here for this method here .

-one
Dec 27 '15 at 16:04
source share



All Articles