lasJac
lasJac

Reputation: 49

How to build a component with conditional child components

I am a bit overwhelmed with my current try of creating a component with (switching) nested components. In my parent component I have a select dropdown menu. Depending on the selection I want to render a component underneath it. This child component will also have a few select elements.

So depending on the selection in my parent component I want to render different selections. And I still need to communicate between the parent and child component, because I sometimes want to pass initial values to the child component.

I am currently using ViewChilds but this feels a bit awkward for this purpose tbh. But are viewchilds the right way for this? In my html I render/dont render the components with ngIf.

Passing initial values (that are included in the child html) for example is throwing errors

Upvotes: 0

Views: 936

Answers (1)

Wesley Trantham
Wesley Trantham

Reputation: 1254

My preferred way is to use the Inputs and Outputs of a component to communicate between them. That is documented in this link. Ignore the section on ngOnChanges, that leads to nothing but trouble.

If you have nested components that you need to switch between, you can use either the hide the unused components with the hidden attribute (shown below) or put an *ngIf on them. The difference is that with hidden attribute the components always exist, where with ngIf it will create/destroy the component every time you switch.

<div>
<component-a [someInput]="someValue" (eventHappened)="handleAEvent" [hidden]="hideA"><component-a>
<component-b [someInput]="someValue" (eventHappened)="handleBEvent" [hidden]="hideB"><component-b>
<component-c [someInput]="someValue" (eventHappened)="handleCEvent" [hidden]="hideC"><component-c>
</div>

You can also create a service that all three components listen to. This link has examples of that. Subsink explained here.

private subsink = new SubSink();

constructor(someService: SomeService) {
  this.subSink.sink = someService.someBehaviorSubject$.subscribe(x=>{
    // do things in this component based on x
  });
}

Upvotes: 2

Related Questions