Angular 2单选按钮到ng-model绑定中断。 以下是我的代码。它第一次更改单选按钮时有效。从第二次选择女性没有效果。
<radio-button [(ngModel)]="isMale" [value]="true" [label]="resource.mySiteDashboard_Male" name="isMale"></radio-button>
<radio-button [(ngModel)]="isMale" [value]="false" [label]="resource.mySiteDashboard_Female" name="isMale"></radio-button>
<div class="market-profile-content" *ngIf="isMale">
</div>
<div class="market-profile-content" *ngIf="!isMale">
</div>
它在角度2 rc-2
中工作正常 下面的是组件的模板。
<div class="radio">
<input [(ngModel)]="value" type="radio" [id]="'radio-'+guid" [attr.name]="name" [disabled]="disabled" (change)="update()" />
<label [attr.for]="'radio-'+guid">
<span>{{label}}</span>
</label>
</div>
代码
import {OnInit, Component, Input, Output, EventEmitter, ElementRef, forwardRef, Provider} from '@angular/core'
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from '@angular/forms';
const RADIO_VALUE_ACCESSOR: Provider = new Provider(NG_VALUE_ACCESSOR, {
useExisting: forwardRef(() => RadioButton),
multi: true
});
@Component({
selector: 'radio-button',
templateUrl: './radioButton.html',
providers: [RADIO_VALUE_ACCESSOR]
})
export class RadioButton implements ControlValueAccessor{
@Input() value: boolean;
@Input() label: string;
@Input() name: string;
@Input() disabled: boolean;
@Output() valueChange: EventEmitter<any> = new EventEmitter();
guid: string;
model: any;
checked: boolean;
onModelChange: Function = () => { };
onModelTouched: Function = () => { };
ngOnInit() {
this.guid = this.generateGuid();
}
generateGuid() {
...
}
update() {
if (!this.disabled) {
this.valueChange.emit(this.value);
this.onModelChange(this.value);
}
}
writeValue(model: any): void {
this.model = model;
this.checked = (this.model == this.value);
}
registerOnChange(func: Function): void {
this.onModelChange = func;
}
registerOnTouched(func: Function): void {
this.onModelTouched = func;
}
}