3

I am trying to implement something like light version of mat-table form Angular Material. And i can't create component inside child component. Here is some code and link to stackblitz at the end.

In some *.html file:

<table uiTable></table>

Base UiTable component:

// ui-table.component.ts

@Component({
  selector: 'table[uiTable]',
  template: `
    <thead uiTableHead></thead>
  `,
})
export class UiTableComponent implements AfterContentInit {

  @ViewChild(UiTableHeadDirective, {static: true}) 
  private tableHead: UiTableHeadDirective;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
  ) {}

  public ngAfterContentInit() {
    const rowFactory = this.componentFactoryResolver.resolveComponentFactory(UiTableRowComponent);

    this.tableHead.viewContainer.clear();
    this.tableHead.viewContainer.createComponent(rowFactory);
  }

}

ui-table-head.directive and ui-table-row.component - just empty angular directive and component with injected ViewContainerRef.

I expect that after ngAfterContentInit is done I will get something like

<table uiTable>
    <thead uiTableHead>
        <tr uiTableRow></tr>
    </thead>
</table>

But instead of it i get

<table uiTable>
    <thead uiTableHead></thead>
    <tr uiTableRow></tr>
    <!--container-->
    <!--container-->
</table>

Why? I call createComponent method from tableHead.viewContainer, but new component creates inside uiTable. What's wrong?

Stackblitz link - https://stackblitz.com/edit/ui-table

2
  • It was historically decided that a dynamically creating component is placed next to the anchor. Anchor in your case is thead Commented Aug 7, 2020 at 13:18
  • 1
    @yurzui oh, ok( is there some way to create a component inside anchor? put anchor inside thead, wait for content init and call createComponent from it? Or maybe something more easy? Commented Aug 7, 2020 at 13:31

1 Answer 1

5

You can forward your dynamically created component to children by using the following snippet:

const componentRef = this.tableHead.viewContainer.createComponent(rowFactory);
this.tableHead.viewContainer.element.nativeElement
                .appendChild(componentRef.location.nativeElement);

Forked Stackblitz

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.