我以[(ngModel)]
显示从服务器接收的数据,但由于它们不会立即出现,因此我多次收到此错误:"错误类型错误:无法读取未定义的属性'title'"。然后我的数据显示在输入字段中。
如何使数据仅在收到时才显示?
模板:
<form [formGroup]="angFormEd" novalidate>
<input type="text" class="form-control" formControlName="titleEd" #titleEd
[(ngModel)]="post.title"/>
<input type="url" class="form-control" formControlName="urlEd" #urlEd pattern="https?://.+"
title="Include http://" [(ngModel)]="post.url"/>
<button (click)="updatePost(titleEd.value, urlEd.value)"
[disabled]=" angFormEd.invalid">
btn btn-primary">Update Post</button>
</form>
元件:
export class GalleryEditComponent implements OnInit {
post: Picture;
constructor(private fb: FormBuilder,
private route: ActivatedRoute, private galleryService: GalleryService) {
}
ngOnInit() {
this.editPost();
}
editPost(): void {
this.route.params.subscribe(params => {
this.galleryService.edit(params['id']).subscribe(res => {
this.post = res;
})
})
}
您混合了模板驱动表单和响应式表单,这是一种不好的做法。
@Angular
支持使用 ngModel 输入属性和 ngModelChange 事件 与反应式表单指令已在 Angular v6 中弃用,并且 将在 Angular v7 中删除。
要么选择patchValue()
,要么setValue()
Updating Angular Forms with patchValue or setValue
editPost(): void {
this.route.params.subscribe(params => {
this.galleryService.edit(params['id']).subscribe(res => {
this.post = res;
this.angFormEd.setValue({titleEd:res.title,urlEd:res.url})
})
})
}
您可以在输入中添加类似*ngIf="post.url"
的条件,以便它仅在加载时显示