Reputation: 1
I all. I'm not an Angular expert and I'm stuck on a problem I can't resolve! :(
This is the scenario: there is a modal with 2 tabs and in each tab there is a form with group of radio buttons. (the component is the same)
This is the const that values TAB1
export const ColorsForRadio: Colors[] = [
{
id: '1',
name: 'red',
checkedFirst: false
},
{
id: '2',
name: 'green',
checkedFirst: true
}
]
This is REST Api Response that values TAB2
{
id: '1',
name: 'red',
checkedFirst: false
},
{
id: '3',
name: 'blue',
checkedFirst: true
},
{
id: '5',
name: 'yellow',
checkedFirst: false
}
This is html
<div *ngFor="let color of colorsForRadio$ | async">
<label class="radio-label">
<input type="radio" formControlName="colorsForRadio" class="radio" [value]="color" [checked]="color.checkedFirst"/>
{{ color.name }}
</label>
</div>
I have 2 kind of problems:
Can someone give me suggestions on how to solve? Thank you
Upvotes: 0
Views: 3124
Reputation: 12950
I would do it by setting the control value in the typescript file, but for that I would need to avoid the async
pipe from the template but rather do the subscription the .ts
and set value to the formControl accordingly.
lets say you have a variable apiData
which you use to get the data from API and use it to loop over in the template.
Something like:
ngOnInit() {
this.parentForm = new FormGroup({
'color': new FormControl()
})
this.getData().subscribe((data) => { // getData() is request to the API
// find the data which was true,
let defaultValue = data.find(eachData => eachData.checkedFirst);
if (defaultValue) {
this.parentForm.get('color').setValue(defaultValue.name)
}
this.apiData = data;
})
}
Your HTML will be like:
<form [formGroup]="parentForm">
<div *ngFor="let eachCheckBox of apiData">
{{eachCheckBox.name}}
<input type="radio" formControlName="color" [value]="eachCheckBox.name">
</div>
</form>
See a working example here: https://stackblitz.com/edit/angular-jlgidp?file=src%2Fapp%2Fapp.component.ts
Upvotes: 1