第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

@ ngIf中的@ViewChild

@ ngIf中的@ViewChild

翻閱古今 2019-09-19 16:39:28
題@ViewChild顯示模板中相應(yīng)元素后最優(yōu)雅的方法是什么?以下是一個(gè)例子。也有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);    }}我有一個(gè)默認(rèn)隱藏其內(nèi)容的組件。當(dāng)有人調(diào)用show()方法時(shí),它變得可見。但是,在Angular 2變更檢測(cè)完成之前,我無法參考viewContainerRef。我通常將所有必需的操作包裝成setTimeout(()=>{},1)如上所示。有更正確的方法嗎?我知道有一個(gè)選項(xiàng)ngAfterViewChecked,但它會(huì)導(dǎo)致太多無用的通話。
查看完整描述

3 回答

?
largeQ

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


查看完整回答
反對(duì) 回復(fù) 2019-09-19
?
守著一只汪

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();

    }


查看完整回答
反對(duì) 回復(fù) 2019-09-19
?
慕虎7371278

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


查看完整回答
反對(duì) 回復(fù) 2019-09-19
  • 3 回答
  • 0 關(guān)注
  • 1218 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)