Hi Lagoon. It's been a frustrating few days for me because I don't think
that bindings on radio buttons are working quite right yet in Angular 2. I
think the key is that radio inputs use a checked="true" attribute on the
checked ones and no attribute at all on the unchecked. So to solve the
problem I used an attribute binding like this:
[attr.checked]="rdoContentRow.selected ? true : null" The null value
leaves the attribute off completely.
I rolled my own component which dynamically lays out the radio buttons.
It is data centric and works on an array of IRadioChoice. parentId is a
unique id which is used for the "name" property so that they work as a
group. I do not use a <form> tag.
Here it is.
//form.IRadioChoice.ts
export interface IRadioChoice {
key: string;
value: string;
text: string;
checked: string;
}
//form.radio.ts
import {Component, OnInit, Input, Output, EventEmitter} from
'@angular/core';
import { IRadioChoice } from './form.IRadioChoice';
@Component({
selector: 'form-radio',
templateUrl: 'app/forms/form.radio.html',
})
//This is a control representing a set of radio buttons
export class FormRadio implements OnInit {
@Input() radioChoices: IRadioChoice[];
@Input() parentId: number;
public name: string;
ngOnInit() : void {
this.name = this.getRadioModelName(this.parentId);
}
public getRadioModelName(parentId: number) : string {
return "RModel" + parentId.toString();
}
public radioChange(itemId: string) {
var _selectedId = '';
for (var ndx = 0; ndx < this.radioChoices.length; ndx++) {
this.radioChoices[ndx].checked = (this.radioChoices[ndx].key ==
itemId) ? 'checked' : null;
if (this.radioChoices[ndx].checked == 'checked') { _selectedId
= this.radioChoices[ndx].value; }
}
}
}
//form.radio.html
<div *ngFor="let rdoContentRow of radioChoices" >
<label [class.columnar]=true [class.col-xs-1]=true>
<input type="Radio" [name]="name"
[id]="rdoContentRow.key"
[attr.checked]="rdoContentRow.selected ? true : null"
(change)="radioChange(rdoContentRow.key)" />
{{rdoContentRow.text}}
</label>
</div>
//And here is where it is called in the parent component. You will need to
import the component and declare it as a directive
<div *ngIf="formContentRow.isRadio" [style.margin-top]="15"
[class.columnar]=true [class]="getClass(formContentRow)" >
<form-radio
[radioChoices]="formContentRow.radioChoices"
[parentId]="formContentRow.id"
(change)="handleChange(formContentRow.radioChoices,
formContentRow.id)"></form-radio>
</div>
On Sunday, July 10, 2016 at 1:39:15 AM UTC-7, Lagoon wish wrote:
>
> how to use checkbox or radio in angular2?
> There is no document in angular.io.
>
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.