0

I have parent component A and a lot (20+) child components, all extending A and being located inside <ng-content></ng-content>. In component A I'm setting value of showContent variable in multiple places.

The problem is that I'm using *ngIf="showContent" in all child components. Because the child components' views are not updated when the value in A is changed I can either:

A) use Output + EventEmitter but I would not like to have

onValueChange(val: boolean) {
  this.showContent = val;
} 

in every child component (20+ times same code);

B) use async pipe. The problem is that I'm setting value in GET/POST subscriptions

this.httpDataHandler.get<...>(...).subscribe(response => {
    // lots of stuff
    showContent = true;
});

Is there any way to use async pipe and remove redundant code from all children?

1 Answer 1

1

I'm guessing you could use a BehaviorSubject here :

showContent = new BehaviorSubject(false)
...
this.httpDataHandler.get<...>(...).subscribe(response => {
  // lots of stuff
  showContent.next(true);
});
...
*ngIf="showContent | async"

or use the ChangeDetectorRef

constructor(private cdr: ChangeDetectorRef) {}
... 
this.httpDataHandler.get<...>(...).subscribe(response => {
  // lots of stuff
  showContent = true;
  this.cdr.markForCheck();
});
...
*ngIf="showContent"

In general when you have these kinds of problems, you are trying to extract data from your observables too soon. You may have a better solution with some refactoring where you would avoid the subscription. But without the full code its hard to tell how...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.