访问* ngIf中的局部变量 [英] access local variable within *ngIf

查看:57
本文介绍了访问* ngIf中的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带下拉菜单的primeng(角度2)对话框.对话框显示时,我想将焦点设置在下拉菜单上.问题似乎是我的div是有条件渲染的.

I have a primeng (angular 2) dialog with a dropdown. I want to set focus to the dropdown when the dialog shows. The problem appears to be that my div is rendered conditionally.

我的代码:

<p-dialog (onShow)="fe.applyFocus()">
  <div *ngIf="selectedItem">
    <button pButton type="button" (click)="fe.applyFocus()" label="Focus"></button>
    <p-dropdown #fe id="reason" [options]="reasonSelects" [(ngModel)]="selectedReason" ></p-dropdown>
  </div>
</p-dialog>

在这段代码中,按钮可以正常工作,但是onShow()(在*ngIf div之外)告诉我fe是未定义的.

In this code the button works fine, but the onShow() (outside the *ngIf div) tells me fe is undefined.

如何访问*ngIf内部的局部变量?

How can I access the local variable inside the *ngIf?

推荐答案

是的,这确实很痛苦.不幸的是,由于* ngIf的工作方式,它完全封装了内部的所有内容(包括其所在的标签).

Yes, this is a real pain. Unfortunately, due to the way *ngIf works, it completely encapsulates everything inside (including the tag it's on).

这表示在ngIf标记上或内部声明的所有内容在ngIf外部均不可见.

This means anything declared on, or inside, the tag with the ngIf will not be "visible" outside of the ngIf.

您甚至不能简单地在ts中放入@ViewChild,因为在第一次运行时它可能不存在...因此,有两种已知的解决方案...

And you can't even simply put a @ViewChild in the ts, because on first run it might not be present... So there are 2 known solutions to this problem...

a)您可以使用@ViewChildren.这将为您提供一个您可以订阅的QueryList,它将在每次tempalte变量更改(即ngIf打开或关闭)时触发.

a) You can use @ViewChildren. This will give you a QueryList that you can subscribe to, which will fire off every time the tempalte variable changes (ie. the ngIf turns on or off).

(html模板)

<div>{{thing.stuff}}</div>
<my-component #thing></my-component>

(ts代码)

@ViewChildren('thing') thingQ: QueryList<MyComponent>;
thing: MyComponent;

ngAfterViewInit() {
    this.doChanges();
    this.thingQ.changes.subscribe(() => { this.doChanges(); });
}

doChanges() {
    this.thing = this.thingQ.first;
}

b)您可以将@ViewChild与setter一起使用.每次ngIf更改时,都会触发设置器.

b) You can use @ViewChild with a setter. This will fire the setter every time the ngIf changes.

(html模板)

<div>{{thing.stuff}}</div>
<my-component #thing></my-component>

(ts代码)

@ViewChild('thing') set SetThing(e: MyComponent) {
    this.thing = e;
}
thing: MyComponent;

这两个示例都应该为您提供一个"thing"变量,您现在可以在ngIf之外的模板中使用该变量.如果发生冲突,您可能想要给ts变量和模板(#)变量起一个不同的名称.

Both of these examples should give you a "thing" variable you can now use in your template, outside of the ngIf. You may want to give the ts variable a different name to the template (#) variable, in case there are clashes.

这篇关于访问* ngIf中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆