我需要动态创建复选框,以等待来自Observable的数据,随着记录的增长,创建复选框。
我还需要在数据库中记录已检查了哪些选项。
我有这样的代码:
component.ts:
user$ = this._store.select(userSelectors.getUserSelected);
this.myForm = this._formBuilder.group({
activities: this._formBuilder.array([]),
// below more controls ...
});
this.user$
.subscribe((user) => {
if (user) {
/* user: {activities: [
{id: '1', name: 'Activity 1', selected: false},
{id: '2', name: 'Activity 2', selected: true},
{id: '3', name: 'Activity 3', selected: false}], ...}
*/
this.myForm.patchValue(user, { emitEvent: false });
}
});
this.activities$
.subscribe((activities) => {
const checkboxControls = activities.map(v => new FormControl(false));
this.myForm.addControl('activities', this._formBuilder.array(checkboxControls));
});
component.html:
<div class="h3 blue-fg">
Select activities
</div>
<div fxLayout="column" fxLayout.xs="column" fxLayoutAlign="start start">
<div formArrayName="activities" *ngFor="let activitie of activities; let i = index">
<mat-checkbox fxFlex="100" class="mt-12" [formControlName]="i">
{{ activitie[i]?.name }}</mat-checkbox>
</div>
</div>
activities: {id: '1', name: 'Activity 1', selected: false}, {id: '2', name: 'Activity 2', selected: true}, {id: '3', name: 'Activity 3', selected: false}];