Error when using setControl or patchValue in angular form array

前端 未结 3 1908
终归单人心
终归单人心 2021-01-23 19:21

Please assist, I have nested form array, se below :

  this.form = this.formBuilder.group({
        projectTitle: [\'\', [Validators.required, Validators.maxLengt         


        
3条回答
  •  不要未来只要你来
    2021-01-23 20:06

    It's difficut help if we don't know the data you have or the data you want to get. I supouse your data was like

    {
      projecTitle:"title",
      projectDescription:"description"
      items:[{
         items:"item 1",
         amount:10
      },
      {
         items:"item 2",
         amount:5
      }]
    
    }
    

    why not use a function to create the form with the data included?

        createForm(data:any)
        {
        this.form = this.formBuilder.group({
                projectTitle: [data?data.projecTitle:'', [Validators.required, Validators.maxLength(300)]],
                projectDescription: [data?data.projectDescription:'', [Validators.required, Validators.maxLength(300)]],
                funding: //See that I change your formBuilder to return
                         //an array, this is because when create the array don't enclosed
                         // by [ ]
    
                        this.formBuilder.array(this._buildFundingItems(data?data.items:null)),
            });
        }
    
        //see that I was to return an array of FormGroup
        _buildFundingItems(items:any[]|null):FormGroup[]
        {
        return items?items.map(x=>{
                return this.formBuilder.group({
                  items: [x.items, [Validators.required, Validators.pattern(this.regexValidation.shortWordRegex)]]
                  amount: [x.amount, [Validators.required, Validators.pattern(this.regexValidation.amountTypeRegex)]]
                }):
     this.formBuilder.group({
              items: ['', [Validators.required, Validators.pattern(this.regexValidation.shortWordRegex)]],,
              amount: ['', [Validators.required, Validators.pattern(this.regexValidation.amountTypeRegex)]],
            });
    
        }
    

    You can see that you call the function createForm sending data: this.createForm(data), create the form with the date. If you call the function sending null: this.createForm(null) create a empy form

提交回复
热议问题