Reputation: 11
How to select button in angular
Here is my code from template.
ngOnInit() {
}
<div class="form-group">
<ng-container *ngFor="let lib of library; let i=index">
<div class="radio">
<input type="radio" id="library-{{i}}" name="lib-books"
(change)="selectOnChange($event)"
[value]="lib">
<label for="library-{{i}}"></label>
</div>
<label for="library-{{i}}">{{lib}}</label>
</ng-container>
</div>
Upvotes: 1
Views: 119
Reputation: 3038
You should use a Form component, either template driven or reactive
Template driven: You use two-way-binding for ngModel
to store the selected value in your form model:
export class AppComponent {
library:string[] = [
'lib1', 'lib2', 'lib3'
];
// note: you should create an interface for that
model = {
books: '',
}
onSubmit () {
// save the selection
}
}
The difference to your code: the two-way binding to the model field [(ngModel)]="model.books"
<div class="form-group" onsubmit="onSubmit()">
<ng-container *ngFor="let lib of library; let i=index">
<div class="radio">
<input type="radio" id="library-{{i}}" name="lib-books"
[(ngModel)]="model.books"
[value]="lib">
<label for="library-{{i}}"></label>
</div>
<label for="library-{{i}}">{{lib}}</label>
</ng-container>
</div>
And don't forget to import the forms
module in app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [ FormsModule ],
})
Check out the StackBlitz for the template driven solution
Reactive forms (my personal preference, especially with the form builder):
export class AppComponent {
library: string[] = [
'lib1', 'lib2', 'lib3'
];
myForm: FormGroup;
constructor(private __fb: FormBuilder) {
this.createForm();
}
createForm() {
this.myForm = this.__fb.group({
book: ''
});
}
onSubmit() {
// save the selection
}
}
Note: the name
attribute of the <input>
needs to be the same as the formControlName
and the <form>
tag needs a [formGroup]
binding.
<form [formGroup]="myForm" onsubmit="onSubmit()">
<div class="form-group">
<ng-container *ngFor="let lib of library; let i=index">
<div class="radio">
<input type="radio"
[value]="lib"
name="book"
formControlName="book"
id="library-{{i}}"
>
</div>
<label for="library-{{i}}">{{lib}}</label>
</ng-container>
</div>
</form>
Check out the StackBlitz for the reactive solution
Upvotes: 1
Reputation: 3934
Create a property isSelected to your lib object and
Sets up two-way data binding to your radio button:
[(value)]="lib.isSelected"
Equivalent to:
(valueChange)="lib.isSelected=$event"
Upvotes: 1