我有一个带有下拉菜单的 primeng(角度 2)对话框。我想在对话框显示时将焦点设置到下拉列表。问题似乎是我的 div
是有条件渲染的。
我的代码:
<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
未定义。
如何访问*ngIf
内的局部变量?
最佳答案
是的,这确实很痛苦。不幸的是,由于 *ngIf 的工作方式,它完全封装了内部的所有内容(包括它所在的标签)。
这意味着带有 ngIf 的标签上或内部声明的任何内容在 ngIf 之外都不会“可见”。
你甚至不能简单地将 @ViewChild 放入 ts 中,因为第一次运行时它可能不存在......所以这个问题有 2 个已知的解决方案......
a) 您可以使用@ViewChildren。这将为您提供一个可以订阅的 QueryList,每次 tempalte 变量发生更改(即 ngIf 打开或关闭)时,该查询列表都会触发。
(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 发生变化时,这都会触发 setter。
(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 变量指定与模板 (#) 变量不同的名称,以防发生冲突。
关于angular2-template - 访问 *ngIf 中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44028873/