如何专注于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
我尝试使用这个问题中建议的设置器,但它不起作用。
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
,您的@ViewChild
将被解决,并将您的检查放入覆盖方法
export class YourComponent implements AfterViewInit {
@ViewChild() currentDaySpentInput: any;
ngAfterViewInit(): void {
// put your logic here
console.log(this.currentDaySpentInput.nativeElement);
}
}