简体   繁体   中英

Angular wrapper component with abstract method

After searching for a while, I did not find anything that I can use.

I need to create a wrapper component, that has some buttons to call methods that will be in the inner component, like this:

wrapper component:

<div class="card">
  <header class="card-header">
    <button (click)="onRefreshClick()">Load</button>
  </header>

  <div class="card-block">
    <ng-content></ng-content>
  </div>

</div>

now I create another component (ChartA for example) that uses this wrapper:

<app-wrapper-card>
  <div style='display: block;'>
        <canvas baseChart class='chart' ....
        </canvas>
  </div>
</app-wrapper-card>

in the onRefreshClick of wrapper component I need to call some method from ChartA component.

How can I do this?

just do this:

<app-wrapper-card (messageEvent)="refreshButtonClicked($event)">
  <div style='display: block;'>
    <canvas baseChart class='chart' ....
    </canvas>
  </div>
</app-wrapper-card>

and add an EventEmitter in your wrapper script

Child component:

Your child component have to implement some abstract class. Then define component-level provider like:

providers: [ {provide: BaseAbstractClass, useExisting: ChartA }]

Parent component:

Query child component with @ContentChild :

@ContentChild(BaseAbstractClass) public baseClass: BaseAbstractClass;

Now you can call methods implemented in child components.

Working example: https://stackblitz.com/edit/angular-2ruhvm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM