I would like to know if is it possible to define a parent component without specifying which child component to use?
Normally i would create a parent component and use the selector of the child component in the html file
parent-component-1.html:
//some logic
<child-component-1-selector></child-component-1-selector>
//some logic
If i follow this approach i have to define which kind of child component i wanna use. But if i wanna use the parent component multiple times with different child components, i have to copy the logic part and create separate parent-components:
parent-component-1.html:
//some logic
<child-component-1-selector></child-component-1-selector>
//some logic
parent-component-2.html:
//some logic (same as above)
<child-component-2-selector></child-component-2-selector>
//some logic (same as above)
I don't like the approach because i would generate code duplicates. Is there a way to define the parent-component without specifying which child component to render and just 'pass' the child component as an argument?
current approach, grand-parent-component.html:
<parent-component-1></parent-component-1>
<parent-component-2></parent-component-2>
suggested approach, grand-parent-component.html:
<parent-component-selector [childcomponent] = "child-component-1"></parent-component-selector>
<parent-component-selector [childcomponent] = "child-component-2"></parent-component-selector>
I hope i have made my self clear about my 'problem'. Maybe you guys can help me and give suggestions about best practices
It sounds like you want to be able to do something like:
<my-custom-panel>
<here-is-one-inner-component>
</my-custom-panel>
And then in another place,
<my-custom-panel>
<some-other-component>
</my-custom-panel>
If i'm reading you right, then you're basically looking at using Angular's content projection.
So, in my example above, I'd write my-custom-panel component to look like this:
@Component({
selector: 'my-custom-panel',
template: `
<div class="wrapper">
<h1>My Heading</h1>
<ng-content></ng-content>
</div>
`
})
export class ....
The trick is that <ng-content> tag, which acts as a marker in the component's template. When using my-custom-panel in another template, any content that appears within the my-custom-panel tag will get projected right next to that <ng-content> tag.
Hopefully, an example will make things clearer. So, in the case of my first example, where the template using my-custom-panel is:
<my-custom-panel>
<here-is-one-inner-component>
</my-custom-panel>
That will get transformed into:
<div class="wrapper">
<h1>My Heading</h1>
<ng-content></ng-content>
<here-is-one-inner-component>
</div>
Is that what you're looking for?