Reputation: 12081
I have tried this many different ways:
<input type="radio" name="group" id="ssnRadio" [checked]="ssn" [(ngModel)]="ssnSelected">
and
<input type="radio" name="group" [checked]="lastName" [(ngModel)]="lastNameSelected" >
There are more radio buttons but they are step up like the above. They are all separate thus not in a *ngFor
in the component I have the following:
ssnSelected: boolean;
userIdSelected: boolean;
lastNameSelected: boolean;
officeSelected: boolean;
roleSelected: boolean;
selectedRow: number;
ngOnInit(){
this.ssnSelected=false;
this.userIdSelected=false;
this.lastNameSelected=false;
this.officeSelected=false;
this.roleSelected=false;
}
And the button has this method in it when it:
search() {
if (this.ssnSelected==true) {
console.log( this.ssn);
this.user = this._searchService.getUserBySSN(this.ssn);
}
if (this.userIdSelected == true) {
console.log(this.userId);
this.user = this._searchService.getUserById(this.userId);
}
So I need to find what radio button was selected so I can call the correct service and pass in a value that is using two way binding to the service.
Upvotes: 0
Views: 669
Reputation: 17894
It seems you need checkbox if it is just true and false situation
and you may use below,
<input type="checkbox" [(ngModel)]="ssnSelected" > SSN Selected
Check this Plunker!!
Update:
based upon comment it seems you need to be selecting just one from a radio button group, You can try below,
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>
<label><input type="radio" name="group" value="ssn" [(ngModel)]="groupVal" > SSN</label>
<label><input type="radio" name="group" value="lastname" [(ngModel)]="groupVal" > Last name</label>
<label><input type="radio" name="group" value="role" [(ngModel)]="groupVal" > SSN Role</label>
<br />
<br />
<button (click)="search()" >Search</button>
`
})
export class AppComponent {
groupVal = "ssn";
name = 'Angular';
search(){
switch(this.groupVal){
case "ssn":
console.log("ssn selected");
break;
case "lastname":
console.log("lastname selected");
break;
case "role":
console.log("role selected");
break;
default:
break;
}
}
}
Updated Plunker!!
Hope this helps!!
Upvotes: 1
Reputation: 234
You need to subscribe to the form changes or individual input changes.
<input type="radio"
name="group"
id="ssnRadio"
[checked]="ssn"
[(ngModel)]="ssnSelected"
(change)="doSomething($event)">
Upvotes: 0