Angular: Append dynamic created component as a child of the target-Element

Discussão em 'Angular' iniciado por Stefan, Janeiro 28, 2025.

  1. Stefan

    Stefan Guest

    I'm implementing a directive to add actions to a mat-table's mat-cell:

    <ng-container matColumnDef="actions">
    <mat-header-cell *matHeaderCellDef></mat-header-cell>
    <mat-cell
    *matCellDef="let row"
    tableActions
    [editAction]="true"
    [actionInputData]="actionInputData"
    [row]="row"
    >
    </mat-cell>
    </ng-container>


    tableActions is the directive. My goal ist to append the actions as a child of mat-cell.

    I've already tried lots of ways and I've searched a lot but haven't found any way to do that in a way, that all works as expected:


    1. I used the _viewContainerRef to create and append the action but the action is alaways added next to the mat-cell and not as a child.

      let componentRef: ComponentRef = this._viewContainerRef.createComponent(component);

    [​IMG]

    1. I used Angular's renderer (Renderer2). It worked to append the component as a child of mat-cell but the mat-icon, mat-tooltip and Angular's standard directives such as *ngIf don't work. It seems so that all directives added to the action's html don't work.

    Here I created the componentRef with the angular core's createComponent-function and appended it to the target-Element (mat-cell)

    let componentRef: ComponentRef<any> = createComponent(component, {
    environmentInjector: this._appRef.injector,
    });

    this._renderer.appendChild(
    this._elementRef.nativeElement as HTMLElement,
    componentRef.location.nativeElement
    );


    [​IMG]

    The edit action's html is:

    <button
    mat-icon-button
    (click)="editRow(row)"
    color="primary"
    matTooltip="{{ 'edit' | translate }}"
    >
    <mat-icon color="primary">edit</mat-icon>
    </button>


    My final question is: How can I append these action-components in a way that all is working as I would implement them directly into the mat-cell?

    Continue reading...

Compartilhe esta Página