不能在AfterViewInit
挂钩上选择动态值。该值可能会在 angulars 生命周期的后期选择;它实际上与AfterViewChecked
钩子一起工作,但这将迫使我设置一个标志,因此它只在第一次运行。这似乎是一个过于复杂的解决方案。我也得到了ExpressionChangedAfterItHasBeenCheckedError
生产,这是有道理的。
input
在没有这些生命周期错误的情况下,在加载组件时选择动态值的简单/正确方法是什么?
查看此stackblitz以获取演示。
这是我使用AfterViewChecked
钩子的一些代码。
app.component.ts
import { Component, ViewChild, AfterViewChecked } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewChecked {
@ViewChild('myInput') public myInput;
public value = 1;
ngAfterViewChecked() {
this.myInput.nativeElement.focus();
this.myInput.nativeElement.select();
}
}
app.component.html
<mat-form-field class='amount' appearance="standard">
<mat-label>Convert</mat-label>
<input #myInput matInput [(ngModel)]='value' />
</mat-form-field>
编辑:我在mat-form-field
代码中添加了它可能是相关的。