Sunday, 16 June 2019

In Angular, how do I insert specific component instances?

So, let's say I have a component, ExampleComponent, that builds a QueryList of SomeOtherComponent components in its content view.

import {Component, ContentChildren, QueryList} from '@angular/core'
import {SomeOtherComponent}                    from '../some-other-component/some-other-component.component'

@Component({
    selector   : 'app-example',
    templateUrl: './example.component.html',
    styleUrls  : ['./example.component.css']
})
export class ExampleComponent {
    @ContentChildren(SomeOtherComponent)
    someOtherComponents: QueryList<SomeOtherComponent>
}

In its template, I have an NgFor that should insert a <hr /> element after each one.

<ng-container *ngFor="let component of someOtherComponents">
    <!-- put component here -->
    <hr />
</ng-container>

So that, for example, this:

<app-example>
    <app-some-other-component>blablabla</app-some-other-component>
    <app-some-other-component>hello world</app-some-other-component>
    <app-some-other-component>testing</app-some-other-component>
</app-example>

Would result in this:

<app-example>
    <app-some-other-component>blablabla</app-some-other-component>
    <hr />
    <app-some-other-component>hello world</app-some-other-component>
    <hr />
    <app-some-other-component>testing</app-some-other-component>
    <hr />
</app-example>

However, this is where the problem shows up. How do I insert that SomeOtherComponent instance? ng-content's select attribute doesn't support component instances, CDK portals don't like me, I don't want to create some complicated solution using templates and require the user to wrap all of their children in templates... What do I do?

Note: There are other ways to insert horizontal rules after components, and feel free to mention those, just make sure to answer the question too. This is just an example.



from In Angular, how do I insert specific component instances?

No comments:

Post a Comment