亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

@ ngIf中的@ViewChild

@ ngIf中的@ViewChild

翻閱古今 2019-09-19 16:39:28
題@ViewChild顯示模板中相應元素后最優雅的方法是什么?以下是一個例子。也有Plunker可用。模板:<div id="layout" *ngIf="display">    <div #contentPlaceholder></div></div>零件:export class AppComponent {    display = false;    @ViewChild('contentPlaceholder', {read: ViewContainerRef}) viewContainerRef;    show() {        this.display = true;        console.log(this.viewContainerRef); // undefined        setTimeout(()=> {            console.log(this.viewContainerRef); // OK        }, 1);    }}我有一個默認隱藏其內容的組件。當有人調用show()方法時,它變得可見。但是,在Angular 2變更檢測完成之前,我無法參考viewContainerRef。我通常將所有必需的操作包裝成setTimeout(()=>{},1)如上所示。有更正確的方法嗎?我知道有一個選項ngAfterViewChecked,但它會導致太多無用的通話。
查看完整描述

3 回答

?
largeQ

TA貢獻2039條經驗 獲得超8個贊

使用QueryList接受的答案對我不起作用。然而,有什么工作是使用ViewChild的setter:


 private contentPlaceholder: ElementRef;


 @ViewChild('contentPlaceholder') set content(content: ElementRef) {

    this.contentPlaceholder = content;

 }

一旦* ngIf變為真,就會調用setter


查看完整回答
反對 回復 2019-09-19
?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

克服這個問題的另一種方法是手動運行變化檢測器。


你先注入ChangeDetectorRef:


constructor(private changeDetector : ChangeDetectorRef) {}

然后在更新控制* ngIf的變量后調用它


show() {

        this.display = true;

        this.changeDetector.detectChanges();

    }


查看完整回答
反對 回復 2019-09-19
?
慕虎7371278

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需要一秒鐘來分配。否則它將是未定義的。


查看完整回答
反對 回復 2019-09-19
  • 3 回答
  • 0 關注
  • 1222 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號