【发布时间】:2019-07-24 23:58:54
【问题描述】:
我有一个简单的网页,其中包含一个表单组,其中很少有控件。在我的 ngOnInit 方法中,我正在发出一个 get 请求以从服务器加载一些数据。在加载此数据之前,我想隐藏表单,并仅在加载数据后显示它。
这是我的.component.ts 文件:
public formGroup = new FormGroup({
firstName: new FormControl('', [
Validators.required,
]),
lastName: new FormControl('', [
Validators.required,
]),
});
这是我的ngOnInit() 方法:
ngOnInit() {
this.route.params.pipe(mergeMap(params => {
this.param1 = params['param'];
this.hideForm(); //I want to implement this method
return this.service.getInfo(this.param1);
})).subscribe(data => {
//this is the success case, i.e. I have loaded the data and obv I want to show the form
this.formGroup.controls['firstName'].setValue(data.firstName);
this.formGroup.controls['lastName'].setValue(data.lastName);
}, err => {
//in the error case the form should stay hidden
});
}
我的component.html 文件的一部分:
<form [formGroup]="formGroup" (ngSubmit)="handleSubmit()">
<mat-form-field>
<input matInput placeholder="Name" formControlName="firstName" required>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Surname" formControlName="lastName" required>
</mat-form-field>
</form>
我已经读到我可以从表单中删除/添加控件,但这对我来说似乎没有必要,不断添加和删除组件而不是隐藏它们。任何想法将不胜感激。
【问题讨论】:
标签: angular typescript angular-material angular-reactive-forms