繁体   English   中英

ngIf中未定义的ViewChild

[英]Undefined ViewChild in ngIf

你如何关注ngIf中的元素?

当页面加载时,此ngIf为true,但仍会出现未定义的错误:

@ViewChild("currentDaySpentInput") currentDaySpentInput: ElementRef;  
// ...
<div class="spending-input" *ngIf="!spentInputComplete">
    <label>How much did you spend today?</label>
    <input [(ngModel)]="currentDay.spent" (keyup)="onKey($event)" #currentDaySpentInput>
</div>

焦点元素

ngOnOnit() {
    this.currentDaySpentInput.nativeElement.focus();
}

错误:

ERROR TypeError: Cannot read property 'nativeElement' of undefined

我尝试使用此问题中建议的setter,但它没有用。

ViewChild在AfterViewInit挂钩之后可用,而不是在Onit上,这就是你得到错误的原因。 https://alligator.io/angular/viewchild-access-component/

@ViewChild("currentDaySpentInput") currentDaySpentInput: ElementRef; 
  ngAfterViewInit() {
    console.log(this.currentDaySpentInput.nativeElement.focus()); // mayo
  }

它应该解决这个问题,如果这不解决问题将不得不看到代码。

您在启动时undefined的原因是因为模板尚未呈现且您的ViewChild无法检测其附件以进行查看

要解决它, AfterViewInit在此处使用AfterViewInit解析@ViewChild ,并将检查放入覆盖方法

export class YourComponent implements AfterViewInit {
   @ViewChild() currentDaySpentInput: any;
   ngAfterViewInit(): void {
    // put your logic here
    console.log(this.currentDaySpentInput.nativeElement);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM