Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何访问可重用组件中的ngModel元素_Angular_Typescript_Angular Ngmodel - Fatal编程技术网

Angular 如何访问可重用组件中的ngModel元素

Angular 如何访问可重用组件中的ngModel元素,angular,typescript,angular-ngmodel,Angular,Typescript,Angular Ngmodel,我的可重用组件中有一个ngModel组件。该字段不是表单的一部分。我想访问它做一些更改。我已经尝试了下面的代码,但它在OnInit中没有定义。你能告诉我怎么取吗 下面的代码返回未定义的 @ViewChild('nameAccessor') ngModel:NgModel; ngOnInit(): void { console.log(this.ngModel); } 模板 <input ngModel (blur)="nameBoxChanged(nameAccessor)" (

我的可重用组件中有一个ngModel组件。该字段不是表单的一部分。我想访问它做一些更改。我已经尝试了下面的代码,但它在OnInit中没有定义。你能告诉我怎么取吗

下面的代码返回未定义的

@ViewChild('nameAccessor') ngModel:NgModel;
ngOnInit(): void {
    console.log(this.ngModel);
}
模板

<input ngModel (blur)="nameBoxChanged(nameAccessor)" (keyup)="nameBoxChanged(nameAccessor)" [ngClass]="{'redBorder':nameBoxValidator}"
      #nameAccessor [disabled]="pageStatus==4" name="name" id="name" type="text" class="form-control" placeholder="{{'movieCategory.placeHolder.name'|translate}}">

试图通过
ViewChild
获取的元素在
OnInit
生命周期事件中未准备就绪。您可以在
AfterViewInit
生命周期事件中获取元素

在调用ngAfterViewInit回调之前设置视图查询

代码块。在
ngAfterViewInit
回调中访问您的字段

@ViewChild('nameAccessor') ngModel:NgModel;

ngOnInit(): void {

}

ngAfterViewInit(): void {
   console.log(this.ngModel);
}

在ngOnInit中,@ViewChild尚未设置。您应该使用ngAfterViewInit。

但如果我们创建示例,我们可以看到ViewChild设置在ngOnInit中,这意味着如果ViewChild是静态查询,那么我们可以在ngOnInitInteresting中获取其值。那么为什么文档中会提到
ngAfterViewInit
?也许不是每次它都能在OnInit?我想他们忘了更新它了。对于旧视图编译器来说,这是正确的。静态内容在创建节点时填充。谢谢你的评论