Angular 5 FormArray get data from database and show rows

后端 未结 1 1256
谎友^
谎友^ 2021-01-15 21:17

I am just a newbie to angular. I have create a event component where user enters the event name with packages. When user creates an event it has the functionality for creati

相关标签:
1条回答
  • 2021-01-15 21:43

    You will have to just loop through data in packages and add it to form.

    After your service you will intialize the loop :-

     getOneEvent(id) {
        this.http.get( this.domain + '/api/event/' + id).subscribe(data => {
          this.event = data['eventname'];
          this.packages = data['packages']; //getting packages as array object
          for(let package of this.packages){
            this.addSection(package)
          }
        });
    
      }
    

    then in your sections function you will pass the same to initSection.

    addSection(package) {
        const control = <FormArray>this.form.get('sections');
        control.push(this.initSection(package));
      }
    

    then finally in your initSection You will assign values

    initSection(package) {
          if (!package) {
            var package = {
              packagename : "",
              packageprice : "",
              packagelimit : ""
            }
          }
          return new FormGroup({
            packagename: new FormControl(package.packagename, [Validators.required, Validators.minLength(5)]),
            packageprice: new FormControl(package.packageprice),
            packagelimit: new FormControl(package.packagelimit)
          });
        }
    

    The if condition is for when you add a blank (a new ) item.

    Also remove the call of addSection from ngOnInit else first row will be left empty.

    0 讨论(0)
提交回复
热议问题