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

时间:2018-02-06 16:36:02

标签: angular angular2-formbuilder

我在从其他组件填充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,它可以正常工作。我该如何解决这个问题?是因为引用还是我必须初始化新的表单组?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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
       })
  });