I am looking to enhance my form by adding a control of array type, but I need to wait for the return of an Observable before mapping the values and integrating them into the form.
The issue with the current code is that it inserts an empty array control even if there is no observable data available.
My goal is to ensure that all observable data has been returned before adding the control. I want to retrieve the last value within subscribe and then insert the control based on the number of users returned.
In my HTML, I want to display checkboxes with the names of users, indicating whether they are tagged or not. This information will be stored in the array along with the user's ID and a boolean value.
component.ts
users$ = this._store.select(usersSelectors.getUsers);
this.myForm = this._formBuilder.group({
// .... controls
});
this.users$.pipe(
filter((data) => !!data),
map(users => this._formBuilder.array(users.map(() => new FormControl(false))))
).subscribe(usersArray =>
this.myForm.addControl('users', usersArray)
);
component.html
<div class="col-md-3">
<label for="users">Users</label>
<div id="users" class="row">
<div class="checkbox" class="col-sm-4"
formArrayName="users"
*ngFor="let item of myForm.get('users').controls; let i = index" >
<label class="checkbox-inline">
<input type="checkbox" [formControlName]="i"> {{ users$[i].name }}
</label>
</div>
Return from users$:
0: {subscriber: false, avatar: "", name: "Paul", id: "eXrrdOfmUGYHFIOVCWjBnAO7PZ52" …}
1: {subscriber: true, avatar: "", name: "Will", id: "NoQMVGnCA6VPc42ksIa6AqZZNWL2" …}
When marking the user, the 'users' control should look like this:
users: [
{eXrrdOfmUGYHFIOVCWjBnAO7PZ52: false}
{NoQMVGnCA6VPc42ksIa6AqZZNWL2: true}
]