Angular 6: Create dynamic reactive form but got an Error: "formGroup expects a FormGroup instance. Please pass one in"

Angular 6: Create dynamic reactive form but got an Error: "formGroup expects a FormGroup instance. Please pass one in"

我目前正在使用 Angular 6 创建一个带有 Reactive Form 的 Accordion。我也在使用 primeNG 的 Accordion 模块。

基于对象(cuList),动态创建FormControl(输入框)。我创建了一个 FormGroup 并使用 FormBuilder 动态添加了组。但是,我在 运行 时间得到了这个错误: (如果 link 不起作用,请查看下面的错误消息)

ERROR Error: "formGroup expects a FormGroup instance. Please pass one in.
   Example:


<div [formGroup]="myGroup">
  <input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({
   firstName: new FormControl()
});"

ERROR TypeError: "this.form is undefined" 3 次。

我根据一些Whosebug的答案尝试了一些方法。它没有解决我的问题。

为了便于阅读,我简化了代码。

组件HTML

<p-accordion #accordion [hidden]="!cuList" [multiple]="true">
    <form *ngIf="cuList" [formGroup]="reportForm" role="form">
        <p-accordionTab header="{{ cu.code }} - {{ cu.name }}" *ngFor='let cu of cuList; let counter = index' [selected]="counter===0">               
            <div class="input-group">
                <input class="form-control"
                    name="wages"
                    placeholder=""
                    formControlName="wages_{{ counter }}"
                    currencyMask
                    [(ngModel)]="cu.wage"
                    [options]="{ prefix: '$ ', thousands: ',', allowNegative: false, precision: 0}"
                    maxlength="15"
                    required />
                <div class="input-group-append">
                    <span class="input-group-text">.00</span>
                </div>
            </div>                      
            <div class="input-group">
                <input class="form-control"
                    name="payments"
                    placeholder=""
                    formControlName="subkPay_{{ counter }}"
                    currencyMask
                    [(ngModel)]="cu.subcontractorPayment"
                    [options]="{ prefix: '$ ', thousands: ',', allowNegative: false, precision: 0}"
                    maxlength="15"
                    required />
                <div class="input-group-append">
                    <span class="input-group-text">.00</span>
                </div>
            </div>
            <div class="input-group">
                <input class="form-control"
                    name="excessPayroll"
                    currencyMask
                    formControlName="exsPay_{{ counter }}"
                    [(ngModel)]="cu.excessPayroll"
                    [options]="{ prefix: '$ ', thousands: ',', allowNegative: false, precision: 0}"
                    maxlength="15"
                    required />
                <div class="input-group-append">
                    <span class="input-group-text">.00</span>
                </div>
            </div>
        </p-accordionTab>
    </form>
</p-accordion>

组件 ts

export class EmployerCuListComponent implements OnInit {
    @ViewChild('accordion') accordion: Accordion;
    reportForm: FormGroup;   // form
    cuList: EmployerCu[];

    constructor(private _fb: FormBuilder) {
    }

    ngOnInit() {
        this._employercuService.getEmployerCu().subscribe(data => {
            this.cuList = data;
        });
        if (this.cuList) {
            this.createForm(this.cuList);
        }
    }

    createForm(cuList: EmployerCu[]) {
        const group = {};

        cuList.forEach((cu, index) => {
            group['wages_' + index] = ['', [Validators.required]];
            group['subkPay_' + index] = ['', [Validators.required]];
            group['exsPay_' + index] = ['', [Validators.required]];
        });
        this.reportForm = this._fb.group(group); // create form with FormBuilder
    }
}

我假设这是一个时间问题?以及对象初始化之前加载的页面?

请帮忙!提前致谢!

我认为这是一个时间问题,我想我知道解决方法.. 变化:

ngOnInit() {
    this._employercuService.getEmployerCu().subscribe(data => {
        this.cuList = data;
    });
    if (this.cuList) {
        this.createForm(this.cuList);
    }
}

对此:

 ngOnInit() {
    this._employercuService.getEmployerCu().subscribe(data => {
        this.cuList = data;
        if (this.cuList) {
            this.createForm(this.cuList);
        }
    });
}

我相信如果没有那个改变,if 语句总是在设置 this.cuList 之前命中,因此永远不会调用 this.createForm。

这是由于 .subscribe() 方法的异步性质。

另供参考: 你可以验证这一点,但放一个

调试器;

在您的 ngOnInit() 顶部声明,如果您这样做,您应该能够在浏览器的开发控制台中单步执行您的代码。

上面的答案很好,应该可以解决问题。