access local variable within *ngIf

情到浓时终转凉″ 提交于 2019-12-06 06:33:30

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

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

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) 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 template)

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

(ts code)

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

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

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

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

(html template)

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

(ts code)

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

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.

You can separate the use of template on NgIf level:

<ng-container *ngIf="expression; else elseTemplate">

</ng-container>
<ng-template #elseTemplate>

</ng-template>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!