gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:02:41 26 4
gpt4 key购买 nike

我有以下 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]
});
}
);
}

我明白了

formGroup expects a FormGroup instance. Please pass one in.

我哪里错了?

更新:

 <form *ngIf="shop" class="m-form m-form--fit m-form--label-align-right" [formGroup]="myFormGroup" novalidate>
...

最佳答案

您必须在创建组件时立即实例化 formgroup,即在构造函数中,否则 Angular 无法找到要绑定(bind)模板属性的内容。

更新

改写:在模板被 Angular 渲染之前,您必须实例化表单组。它比 Angular 1.x 更严格,如果在 html 表单渲染时无法评估模板绑定(bind)中的表达式,则会抛出错误。

由于您在模板中使用 *ngIf="shop" 我想说这意味着 shop before 变为非空then() 被执行 - 也许最初,也许通过其他函数 - 它不在您提供的代码中,所以我无法指出它。

您想要做的是使用某些服务获取的一些数据来初始化表单。这完全没问题 - 但仍然没有理由推迟创建控件。只需在构造函数中创建它们,然后在 ngOnInit 中使用 FormGroup's 设置值即可。 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'});
}

}

app.component.html

<form [formGroup]="formGroup">
<input type="text" formControlName="title">
</form>

关于angular - 如何在 Angular 4 中初始化表单组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com