如何用角度设置数组形式的值 [英] how to set value in array form with angular

查看:74
本文介绍了如何用角度设置数组形式的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样在数组中设置值:

I want to set value in array like this:

this.form.controls[name].setValue('name')

但是我正在使用数组形式,即使我通过了especific数组形式的索引也无法正常工作

but I am working with array forms, and this is not working, even if I pass index of the especific array form

例如,这是我的表单数组,我要做的是在函数中设置值

for example this is my form array and I want to do is to set value in a function

user: FormGroup;
  users: FormGroup;

  constructor(private fb: FormBuilder) {}
  ngOnInit() {
    this.user = this.buildGroup();
    this.users = this.fb.group({
      data: this.fb.array([this.user])
    });
  }
  get fData() {
    return this.users.get('data') as FormArray;
  }
  buildGroup() {
    return this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      account: this.fb.group({
        email: ['', Validators.required],
        confirm: ['', Validators.required]
      })
    });
  }
setValue(index) {
   this.fData[index].controls[name].setValue('name')
  }
  onSubmit() {
    this.fData.push(this.buildGroup());
    const {valid, value} = this.fData;
    console.log(valid, value);
  }

但是this.fData [index] .controls [name] .setValue('name')无效

but this.fData[index].controls[name].setValue('name') this is not working

推荐答案

对于数组,您需要使用setControl.像这样:

For arrays, you need to use setControl. Something like this:

    this.productForm = this.fb.group({
        productName: ['', [Validators.required,
                           Validators.minLength(3),
                           Validators.maxLength(50)]],
        productCode: ['', Validators.required],
        starRating: ['', NumberValidators.range(1, 5)],
        tags: this.fb.array([]),
        description: ''
    });

    ...

    // Update the data on the form
    this.productForm.patchValue({
        productName: this.product.productName,
        productCode: this.product.productCode,
        starRating: this.product.starRating,
        description: this.product.description
    });
    this.productForm.setControl('tags', this.fb.array(this.product.tags || []));

这篇关于如何用角度设置数组形式的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆