访问 *ngIf 中的局部变量

2024-04-11

我有一个带有下拉菜单的 primeng(角度 2)对话框。我想在对话框显示时将焦点设置到下拉列表。问题似乎是我的div有条件地呈现。

My code:

<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() (在*ngIfdiv) 告诉我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 变量指定与模板 (#) 变量不同的名称,以防发生冲突。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

访问 *ngIf 中的局部变量 的相关文章