【问题标题】:Angular - How to set values in form array of slide toogleAngular - 如何在幻灯片切换的表单数组中设置值
【发布时间】:2021-12-27 03:38:36
【问题描述】:

我得到了一个响应式表单,其中包含一个名为 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,因此我有一个名为 canaisHabilitados 的字符串数组。

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 中使用它,查看哪个幻灯片工具被选中了。

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]}}

【问题讨论】:

    标签: angular formarray


    【解决方案1】:

    设置值的数组

    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)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 2015-06-18
      • 1970-01-01
      相关资源
      最近更新 更多