例如,我的模板看起來像 -Angular2 - 如何訪問尚未呈現的子輸入元素?
<div #parent>
<button (click)="showInput()"> Show </button>
<input #inp *ngIf="showInpField" />
</div>
這是我compoent看起來像:
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'some-component',
templateUrl: './template.html',
})
export class SomeComponent {
@ViewChild('inp') inpField: any;
showInpField = false;
constructor() {}
showInput(){
this.showInpField = true;
// This doesn't work
this.qaTitle.inpField.focus();
}
}
在這種情況下,焦點不會工作,因爲輸入元素仍然沒有被渲染。我意識到在該行上使用超時會起作用,但不知何故,我覺得這不是一個好辦法。
我想我以某種方式檢測父div的變化,並在那個事件我應該做的焦點操作。我會怎麼做?我覺得QueryList可以幫助,但我無法弄清楚在這種情況下如何使用它!
我一直在尋找這樣的事情。謝謝。我現在試試看,如果有效,請勾選綠色。 – user1532043
但是等一下,會不會this.viewContainerRefs.changes.subscribe工作,因爲該元素最初沒有呈現。 – user1532043
真棒!謝謝。 – user1532043