我得到了一个具有名为enabledChannels的表单数组的反应表单。
ngOnInit(): void {
this.form = this._formBuilder.group({
name: [this.notificacao.name, Validators.required],
nabledChannels: this.buildChannelArray()
});
}
buildChannelArray() {
const values = this.canaisHabilitados.map(() => new FormControl(false));
return this._formBuilder.array(values, this.requiredMinCheckboxChannel(1));
}
我需要将通道的名称发送到我的api,因此我有一个名为canaisHabiligados的字符串数组。
canaisHabilitados = ['PUSH', 'SMS'];
当我提交我的表格时,我需要发送我的频道名称,所以我更改了我的提交,它运行得很好:
onSubmit() {
let valueSubmit = Object.assign({}, this.form.value);
valueSubmit = Object.assign(valueSubmit, {
enabledChannels: valueSubmit.enabledChannels
.map((valor, index) => (valor ? this.canaisHabilitados[index] : null))
.filter((valor) => valor !== null),
});
...
}
但是,当我编辑我的寄存器时,我需要获得formArray的值,再次作为布尔值的数组,这样我就可以在模板HTML中使用它,以查看检查了哪个幻灯片toogle。
HTML
<div *ngFor="let channel of form.get('enabledChannels')?.['controls']; let i = index" formArrayName="enabledChannels">
<mat-slide-toggle (click)="toogleChannel(canaisHabilitados[i])" [formControlName]="i" [checked]="channel.value">
{{canaisHabilitados[i]}}
设置值的数组
export class RestrainComponent implements OnInit, OnDestroy {
validateForm!: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.validateForm = this.fb.group({
restrainArr: this.fb.array([])
});
this.restrainArr.push(this.restrainListOne);
}
get restrainListOne(): FormGroup {
return this.fb.group({
name: ['', [Validators.required, Validators.maxLength(100)]],
inhibitionSort: [''],
status: [false],
});
}
get restrainArr(): FormArray {
return this.validateForm.get('restrainArr') as FormArray;
}
// set value
setRestrain(i){
this.restrainArr.at(i).get('status').setValue(true)
}
}