How to catch an event trigger inside of a <ng-container>

非 Y 不嫁゛ 提交于 2019-12-24 10:48:33

问题


Good afternoon guys, i have the following structure:

parent.html

<child-component>
<ng-template let-dataSource="dataSource" let-displayedColumns="dc">
  <mat-table class="cruds-table" [dataSource]="dataSource" matSort fusePerfectScrollbar>

      <ng-container matColumnDef="name">
        <mat-header-cell *matHeaderCellDef mat-sort-header>Nome</mat-header-cell>
        <mat-cell *matCellDef="let crud">
          <p class="text-truncate" (click)="clica()">{{crud.name}}</p>
        </mat-cell>
      </ng-container>
 [...]</ng-template>
</child-component>

child.html

<ng-container *ngTemplateOutlet="contentTable;context:{dataSource: dataSource, dc: displayedColumns}"></ng-container>

child.ts

clica(){
    alert('clicked');
}

when I click on it, the function is triggered on the parent component, i know i can use View to get the child component and use as child.clica(), but i have many functions and i would prefer to bind all the events inside of this container to the child component.

Is there any way to do this?

Sorry if it's confusing, it's complicated to explain. Thanks!


回答1:


If you are clear with javascript functionality and Angular, Here is the trickier way to go :

constructor(app:AppComponent){ //<-- get the ref of the parent component
    app['clic'] = this.clic; //<-- declare function and bind our function 
    this.name = 'myself';
}

clic(){
    alert('clicked');
}

ngOnDestroy() {
    delete this.app['clic']; // <-- get rid of the function from parent component, when we are done
}

WORKING DEMO

NOTE : I have also explored the solution just for fun, but it's really cool

You can load parent component in child in many ways DO READ.




回答2:


You can set up an EventEmitter on your child component and bind to that event in your parent component.

inside child.ts

@Output
clickEvent: EventEmitter<any> = new EventEmitter();
...
click() {
    this.clickEvent.emit(eventArgs);
}

parent.html

<child-component (clickEvent)="someFuncOnParent()"></child-component>

parent.ts

someFuncOnParent(event) { 
    //event args can be passed to parent here 
}

If you're trying to go the other direction you can use the @Input on the child with an EventEmitter, like so.

child.ts

@Input
clica: EventEmitter<any> = new EventEmitter();

ngOnInit() {
    this.clica.subscribe(() => alert('clicked'));
}

parent.html

<child-component [clica]="parentClickEvent">
<ng-template>
  <button (click)="parentClick()">
    Click Me!
  </button>
</ng-template>
<child-component>

parent.ts

parentClickEvent: EventEmitter<any> = new EventEmitter();

parentClick() {
    this.parentClickEvent.next();
}

https://stackblitz.com/edit/angular-oyxkwb



来源:https://stackoverflow.com/questions/57434890/how-to-catch-an-event-trigger-inside-of-a-ng-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!