创建具有可观察的回报的动态复选框

时间:2018-09-24 16:40:17

标签: angular typescript angular-reactive-forms

我需要动态创建复选框,以等待来自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>

我正在寻找的解决方案:

  1. 在创建新活动时更新复选框,并将这样的对象保存到我的数据库中:
activities:
{id: '1', name: 'Activity 1', selected: false},
{id: '2', name: 'Activity 2', selected: true},
{id: '3', name: 'Activity 3', selected: false}];
  1. 在编辑表单时,它应显示已标记的活动,并可以通过在Observable中注册的活动的返回来标记或取消标记活动。

0 个答案:

没有答案