我正在使用FormGoup
,我想将选定的checkbox
值插入一个数组,并希望也控制它的值,但是我在做一些错误,我想请检查我的代码并让我知道我必须在哪里进行更改。
谢谢
component.ts
import {Component} from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { map } from 'rxjs/operators';
@Component({
selector: 'checkbox-overview-example',
templateUrl: 'checkbox-overview-example.html',
styleUrls: ['checkbox-overview-example.css'],
})
export class CheckboxOverviewExample {
form;
controlNames;
selectedNames$;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
'one': false,
'two': false,
'three': false,
'four': false
})
this.controlNames = Object.keys(this.form.controls).map(_=>_)
this.selectedNames$ = this.form.valueChanges.pipe(map(v => Object.keys(v).filter(k => v[k])));
}
}
component.html
<ng-container [formGroup]="form">
<mat-checkbox *ngFor="let controlName of controlNames" [formControlName]="controlName">{{controlName}}</mat-checkbox>
</ng-container>