Angular - add component after another (in code)

I am trying to create a large system using Angular. Thus, you can have several containers separated by a strip, which allows the user to resize them.

At the moment, I have a solution that requires the developer to write this HTML code:

<split-pane>
    <container>Some content</container>
    <separator></separator>
    <container>Another content</container>
    <separator></separtor>
    <container>Content ?</container>
<split-pane>

split panel , container and separator are all angular2 custom components. a dashboard template is just

<ng-content></ng-content>

and I access the container and separtor inside the split panel using @ContentChildren(ContainerComponent)and@ContentChildren(SeparatorComponent)

, .

, HTML-:

<split-pane>
    <container>Some content</container>
    <container>Another content</container>
    <container>Content ?</container>
<split-pane>

. , Angular. Transclusion, , , .

?

+4
2

- , angular , :

  ...
  entryComponents: [SeparatorComponent]
})
export class AppModule {}

, :

 <split-pane>
   <container>Some content</container>
   <container>Another content</container>
   <container>Content ?</container>
 </split-pane>

- container, ViewContainerRef container. SplitPaneComponent

@ContentChildren(ContainerComponent, { read: ViewContainerRef }) containersRefs: QueryList<ViewContainerRef>;

ComponentFactoryResolver, factory ViewContainers, SeparatorComponent container. , :

ngAfterContentInit() {
  this.containersRefs.forEach((vcRef: ViewContainerRef, index: number, arr: any[]) => {
    if(index === arr.length - 1) {
        return;
    }

    let compFactory = this.resolver.resolveComponentFactory(SeparatorComponent);
    let compRef = vcRef.createComponent(compFactory);
    this.separators.push(compRef);
  })
}

+3

, ngFor .

ngFor last:

<template ngFor let-item [ngForOf]="items" let-i="index" let-last="last">
  <container>{{item.content}}</container>
  <separator *ngIf="!last"></separator>
</template>

items , .

+1

Source: https://habr.com/ru/post/1675691/


All Articles