如何在Angular 4中初始化表单组?

Bur*_*rak 2 angular2-formbuilder angular

我有以下ngOnInit方法:

ngOnInit() {
    this.countries = this.sharedService.getCountries();
    this.shopService.getCurrentShopFromCache().then(shop => {
        this.shop = shop;
        this.myFormGroup = this.fb.group({
            name: [this.shop.name[this.shop.defaultLanguage.code], [Validators.required]],
            address: [this.shop.address.address],
            city: [this.shop.address.city],
            state: [this.shop.address.state],
            country: [this.shop.address.country, [Validators.required]],
            phone: [this.shop.phone],
            email: [this.shop.email],
            website: [this.shop.social.website],
            twitter: [this.shop.social.twitter],
            facebook: [this.shop.social.facebook],
            instagram: [this.shop.social.instagram],
            foursquare: [this.shop.social.foursquare]
        });
    }
    );
}
Run Code Online (Sandbox Code Playgroud)

我越来越

formGroup expects a FormGroup instance. Please pass one in.
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

更新:

 <form *ngIf="shop" class="m-form m-form--fit m-form--label-align-right" [formGroup]="myFormGroup" novalidate>
                       ... 
Run Code Online (Sandbox Code Playgroud)

Ale*_*nov 10

您必须在组件创建时即在构造函数中立即实例化formgroup,否则angular根本找不到绑定模板属性的内容。

更新

改写:您必须实例化表单组,然后才能通过angular渲染模板。它比angular 1.x严格,如果无法在html表单呈现时评估模板绑定中的表达式,则会引发错误。

由于您正在*ngIf="shop"模板中使用,我想说这意味着在执行then()之前shop转弯不为null- 也许最初是通过其他函数执行的-它不在您提供的代码中,因此我无法指出。

您要尝试的是使用某些服务获取的某些数据来初始化表单。很好-但是仍然没有理由推迟控件的创建。只需在构造函数中创建它们,然后在ngOnInit中使用FormGroup的 setValue()patchValue()reset()设置值-取决于您的实际需求。下面只是一个想法,您需要将其调整为表单结构。

app.component.ts

import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

    formGroup: FormGroup;

    constructor(fb: FormBuilder) {
        this.formGroup = fb.group({
            title: fb.control('initial value', Validators.required)
        });
    }

    ngOnInit(): void {
        this.formGroup.reset({title: 'new value'});
    }

}
Run Code Online (Sandbox Code Playgroud)

app.component.html

<form [formGroup]="formGroup">
    <input type="text" formControlName="title">
</form>
Run Code Online (Sandbox Code Playgroud)