为了账号安全,请及时绑定邮箱和手机立即绑定

@ 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条经验 获得超7个赞

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


 private contentPlaceholder: ElementRef;


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

    this.contentPlaceholder = content;

 }

一旦* ngIf变为真,就会调用setter


查看完整回答
反对 回复 2019-09-19
?
守着一只汪

TA贡献1872条经验 获得超3个赞

克服这个问题的另一种方法是手动运行变化检测器。


你先注入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 关注
  • 1138 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信