Angular 2 Form “Cannot find control with path”

前端 未结 5 1509
无人共我
无人共我 2020-11-30 03:36

I try to make a dynamic form (so you can limitless add items to a list), but somehow the content of my list is not getting send because it can\'t find the control with path:

5条回答
  •  被撕碎了的回忆
    2020-11-30 04:31

    A simple example with FormArray @ stackblitz (gist'd below)

    app.component.ts

    import { Component,OnInit } from '@angular/core';
    import { FormGroup, FormControl, FormArray, FormBuilder, Validators } from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent implements OnInit {
      fg: FormGroup;
      constructor(private fb: FormBuilder){}
      ngOnInit() {
      this.fg = this.fb.group({
        address: this.fb.group({
          street: ['', Validators.required],
        }),
        aliases: this.fb.array([])
      });
      const fa = (this.fg.get('aliases')as FormArray);
      this.addNewAlias();
      }
      addNewAlias(){
        const fa = (this.fg.get('aliases')as FormArray);
        fa.push(this.fb.group({
          name: ['', Validators.required]
        }));
      }
      deleteAlias(i:number){
        const fa = (this.fg.get('aliases')as FormArray);
        fa.removeAt(i);
        if(fa.length===0) this.addNewAlias();
      }
    }
    

    app.component.html

    Nested in Group:

    Nested in Array:

    form valid: {{fg?.valid}}

提交回复
热议问题