3 回答

TA貢獻2039條經驗 獲得超8個贊
使用QueryList接受的答案對我不起作用。然而,有什么工作是使用ViewChild的setter:
private contentPlaceholder: ElementRef;
@ViewChild('contentPlaceholder') set content(content: ElementRef) {
this.contentPlaceholder = content;
}
一旦* ngIf變為真,就會調用setter

TA貢獻1872條經驗 獲得超4個贊
克服這個問題的另一種方法是手動運行變化檢測器。
你先注入ChangeDetectorRef:
constructor(private changeDetector : ChangeDetectorRef) {}
然后在更新控制* ngIf的變量后調用它
show() {
this.display = true;
this.changeDetector.detectChanges();
}

TA貢獻1802條經驗 獲得超4個贊
上面的答案對我不起作用,因為在我的項目中,ngIf在輸入元素上。我需要訪問nativeElement屬性,以便在ngIf為true時關注輸入。ViewContainerRef上似乎沒有nativeElement屬性。這是我做的(遵循@ViewChild文檔):
<button (click)='showAsset()'>Add Asset</button>
<div *ngIf='showAssetInput'>
<input #assetInput />
</div>
...
private assetInputElRef:ElementRef;
@ViewChild('assetInput') set assetInput(elRef: ElementRef) {
this.assetInputElRef = elRef;
}
...
showAsset() {
this.showAssetInput = true;
setTimeout(() => { this.assetInputElRef.nativeElement.focus(); });
}
我在聚焦之前使用了setTimeout,因為ViewChild需要一秒鐘來分配。否則它將是未定義的。
- 3 回答
- 0 關注
- 1222 瀏覽
添加回答
舉報