我想使用单选按钮在表单中使用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/>
model.options初始值为1
任何想法 ?
注意 – 单选按钮绑定现在是RC4向前支持的功能 – 请参阅
this answer
原文链接:https://www.f2er.com/angularjs/146137.html单选按钮示例使用自定义RadioControlValueAccessor类似于CheckBoxControlValueAccessor(使用Angular 2 rc-1更新)
应用程序
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; } }
资料来源:https://github.com/angular2-school/angular2-radio-button
Plunker现场演示:http://plnkr.co/edit/aggee6An1iHfwsqGoE3q?p=preview