视图子项不适用于Modal-Angular中的Element Ref



我有一个模型,它是一个表单,我正在尝试预填充它。我认为View Child无法识别Modal的元素Ref,我遇到了类似这样的问题

core.js:5980 ERROR TypeError: Cannot read property 'setValue' of undefined
at EditPostComponent.ngOnInit (edit-post.component.ts:22)
at callHook (core.js:2486)
at callHooks (core.js:2457)
at executeInitAndCheckHooks (core.js:2408)
at refreshView (core.js:9207)
at refreshEmbeddedViews (core.js:10312)
at refreshView (core.js:9216)
at refreshComponent (core.js:10358)
at refreshChildComponents (core.js:8989)
at refreshView (core.js:9242)

是否有其他方法可以针对元素ref

组件

export class EditPostComponent implements OnInit {
@ViewChild('e') queryForm: NgForm;
id: string;
originalPost: Post;
constructor(private usService: UsaService) {}
ngOnInit() {
this.id = this.usService.editPost;
this.originalPost = this.usService.getSinglePost(this.id);
console.log(this.originalPost);
this.queryForm.setValue({
title1: 'Testing ',
body1: 'This is body',
postUrl1: 'http',
});
}
editForm(form: NgForm) {
console.log(form.value);
}
}

ViewChild默认情况下在运行第一次更改检测后解决查询,因此有两种解决此问题的方法

  1. ViewChild中使用static选项(如果使用角度8或更高(
@ViewChild('e', { static: true }) queryForm: NgForm;
  1. 使用ngAfterViewInit生命周期而不是ngOnInit来设置您的值

最新更新