【问题标题】:Reactive Form Management In AngularAngular 中的反应式表单管理
【发布时间】:2021-09-20 17:59:30
【问题描述】:

我不知道如何管理我的表单。想象一下 7 个初始值的形式:

  • 姓名
  • 公司
  • 电子邮件
  • 地址
  • 产品(可重复)
  • 序列号(可重复)
  • 退货运输说明

有一个按钮可以创建产品和序列号输入字段组件的新实例(以防有更多产品)。这意味着我需要创建另一个组件来制作嵌套表单。我遇到的问题是我不知道我该如何应对。

我目前像这样记录我的值:

    console.log(this.parentForm.controls.name.value);
    console.log(this.parentForm.controls.company.value);
    console.log(this.parentForm.controls.email.value);
    console.log(this.parentForm.controls.address.value);
    console.log(this.parentForm.controls.returnInstructions.value);

但我仍在试图弄清楚如何存储我的 Product 和 SN 值(以及是否有可能删除它们)。我正在考虑将它们存储在一组对象中,这些对象将被发送到父组件(具有主窗体的那个)。数组看起来像这样:{Object1: product1, SN1, Object2: product2, SN2...} 但是,我不知道如何构建它。

【问题讨论】:

    标签: javascript angular algorithm


    【解决方案1】:

    这是表单数组的完美用例。下面的验证只是一个例子。

    
      get products(): FormArray {
        return this.fooForm.get('products') as FormArray;
      }
    
      constructor(private fb: FormBuilder) { }
    
      ngOnInit(): void {
        this.fooForm = this.fb.group({
          name: ['', [Validators.required, Validators.minLength(3)]],
          company: ['', [Validators.required, Validators.maxLength(50)]],     
          email: ['', [Validators.required, Validators.email]],
          address: '',
          products: this.fb.array([this.buildProduct()])
        });
      }
    
      buildProduct(): FormGroup {
        return this.fb.group({
          name: ['', Validators.required],
          serialNumber: ['', Validators.required],
        });
      }
    
    

    然后像这样删除:

      removeProduct(index: number): void {
        this.products.removeAt(index);
      }
    

    像这样添加产品:

      addProduct(): void {
        this.products.push(this.buildProduct());
      }
    

    【讨论】:

    • 非常感谢!我忘了我什至问过这个问题。我做了一些研究,这正是我最终做的!
    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 2020-05-05
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    相关资源
    最近更新 更多