我试图了解模型更改后等待模板在 Angular 2 应用程序中更新的最佳方法。
@Component{
template : `<button type="button" (click)="handleClick()">Click</button>
<div *ngIf="!hidden">
<input type='text' #eleInput/>
</div>`
}
export class Sample{
private hidden: boolean = true;
@ViewChild('eleInput') eleInput: ElementRef;
constructor(){}
handleClick(){
this.hidden = false;
//nativeElement is undefined here
this.eleInput.nativeElement.focus();
//nativeElement is defined here
setTimeout(() => {
this.eleInput.nativeElement.focus();
});
}
}
在上面的代码中使用 setTimeout 似乎很 hacky,所以我想知道是否有更好的方法。
谢谢!
最佳答案
没有办法等待模板更新。
你可以注入(inject)ChangeDetectorRef
constructor(private cdRef:ChangeDetectorRef) {}
然后调用
this.cdRef.detectChanges();
据我所知,模板会在调用返回时更新。
关于javascript - 如何正确等待模板在 Angular 2 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40072462/