How do you bind to an EventEmiter
or Subject
in a child component when that component is contained within an *ngIf
?
I've got a component as a @ViewChild()
inside an *ngIf
@ViewChild('foo')
foo: FooComponent;
<div *ngIf="someToggle">
<app-foo #foo/>
</div>
My FooComponent
has a Subject
to notify the parent component when something changes:
export class FooComponent
{
@Output()
somethingChanged = new Subject();
}
Now, in my parent component, when I try to subscribe to the somethingChanged
subject I get an error because this.foo
is undefined. In the example below there are two places I could subscribe, in the ngAfterViewInit
which would be the place to do it if the child component wasn't in an *ngIf
, but it is so it's undefined at this point.
The second place to subscribe is in my showTheFoo()
method which flips the switch to show the component, but the viewChild is still undefined immediately after that because angular hasn't processed the change yet, so how do I subscribe after the change has been processed and the component is added to the DOM?
export class ParentComponent implements AfterViewInit
{
@ViewChild('foo')
foo: FooComponent;
someToggle = false;
ngAfterViewInit(): void {
// this.foo === undefined.
// this makes sense because it's hidden
}
showTheFoo()
{
this.someToggle = true;
// this.foo is still undefined.
// this also makes sense, because although we've flipped the switch
// angular hasn't processed the change,
// but how do I subscribe after it's been shown?
this.foo.somethingChanged.subscribe(()=>{});
}
}