3 回答

TA貢獻(xiàn)2039條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用QueryList接受的答案對(duì)我不起作用。然而,有什么工作是使用ViewChild的setter:
private contentPlaceholder: ElementRef;
@ViewChild('contentPlaceholder') set content(content: ElementRef) {
this.contentPlaceholder = content;
}
一旦* ngIf變?yōu)檎?,就?huì)調(diào)用setter

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

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
上面的答案對(duì)我不起作用,因?yàn)樵谖业捻?xiàng)目中,ngIf在輸入元素上。我需要訪問nativeElement屬性,以便在ngIf為true時(shí)關(guān)注輸入。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,因?yàn)閂iewChild需要一秒鐘來分配。否則它將是未定義的。
- 3 回答
- 0 關(guān)注
- 1218 瀏覽
添加回答
舉報(bào)