将数据从其他组件传递到FormBuilder

问题描述 投票:0回答:1

我有从其他组件填充Formbuilder的问题。

component1:这是调用需要显示数据的组件的组件:

    import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
    import { component2 } from '../component2.component';

    export class component1 implements OnInit {        
        constructor(private modalService: NgbModal, private cocf: component2)

          showModal(id: number) {
            const modalRef = this.modalService.open(component2);
            this.cocf.fillData(id);
          }
}

component2:这里是需要显示数据的组件:

        import { DataService } from '../../../services/data.service';
        import { NgbModal, NgbActiveModal, NgbModule, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
        import { Validators, FormGroup, FormArray, FormBuilder, FormControl, ValidatorFn } from '@angular/forms';

        export class component2 implements OnInit {        
        showData: FormGroup;

        constructor( private modalService: NgbModal, public _fb: FormBuilder)

        ngOnInit(){
        this.showData = this._fb.group({
         here are default values
        })
        }

    fillData(id){
        this.DataService.getDataById(id)
          .subscribe(data => {
            this.data = data
            console.log(this.data);
              this.showData.pathValue({
               here are updated values of initial data
           })
          });
    }
}

console.log()中的数据没问题。我得到的错误:

ERROR TypeError: Cannot read property 'patchValue' of undefined

如果我在component2中调用函数fillData,它可以正常工作。我该如何解决这个问题?是因为引用还是我必须初始化新的表单组?任何帮助将不胜感激。

angular angular2-formbuilder
1个回答
0
投票

我认为这: const modalRef = this.modalService.open(component2);

应该是这样的:

const modalRef = this.modalService.open(this.cocf);

另外,您是否尝试在fillData方法中移动formBuilder,如下所示:

fillData(id){
    this.showData = this._fb.group({
       here are default values
    });

    this.DataService.getDataById(id)
      .subscribe(data => {
        this.data = data
        console.log(this.data);
          this.showData.pathValue({
           here are updated values of initial data
       })
  });
© www.soinside.com 2019 - 2024. All rights reserved.