@ ngIf中的@ViewChild

@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,但它会导致太多无用的通话。


翻阅古今
浏览 1131回答 3
3回答

largeQ

使用QueryList接受的答案对我不起作用。然而,有什么工作是使用ViewChild的setter:&nbsp;private contentPlaceholder: ElementRef;&nbsp;@ViewChild('contentPlaceholder') set content(content: ElementRef) {&nbsp; &nbsp; this.contentPlaceholder = content;&nbsp;}一旦* ngIf变为真,就会调用setter

守着一只汪

克服这个问题的另一种方法是手动运行变化检测器。你先注入ChangeDetectorRef:constructor(private changeDetector : ChangeDetectorRef) {}然后在更新控制* ngIf的变量后调用它show() {&nbsp; &nbsp; &nbsp; &nbsp; this.display = true;&nbsp; &nbsp; &nbsp; &nbsp; this.changeDetector.detectChanges();&nbsp; &nbsp; }

慕虎7371278

上面的答案对我不起作用,因为在我的项目中,ngIf在输入元素上。我需要访问nativeElement属性,以便在ngIf为true时关注输入。ViewContainerRef上似乎没有nativeElement属性。这是我做的(遵循@ViewChild文档):<button (click)='showAsset()'>Add Asset</button><div *ngIf='showAssetInput'>&nbsp; &nbsp; <input #assetInput /></div>...private assetInputElRef:ElementRef;@ViewChild('assetInput') set assetInput(elRef: ElementRef) {&nbsp; &nbsp; this.assetInputElRef = elRef;}...showAsset() {&nbsp; &nbsp; this.showAssetInput = true;&nbsp; &nbsp; setTimeout(() => { this.assetInputElRef.nativeElement.focus(); });}我在聚焦之前使用了setTimeout,因为ViewChild需要一秒钟来分配。否则它将是未定义的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS