Angular pass callback function to child component as @Input similar to AngularJS way

后端 未结 10 1605
庸人自扰
庸人自扰 2020-11-27 10:22

AngularJS has the & parameters where you could pass a callback to a directive (e.g AngularJS way of callbacks. Is it possible to pass a callback as an @Input

10条回答
  •  难免孤独
    2020-11-27 10:33

    In some cases, you might need business logic to be performed by a parent component. In the example below we have a child component that renders table row depending on the logic provided by the parent component:

    @Component({
      ...
      template: '',
      directives: [TableComponent]
    })
    export class ParentComponent {
    
     // Pay attention on the way this function is declared. Using fat arrow (=>) declaration 
     // we can 'fixate' the context of `getColor` function
     // so that it is bound to ParentComponent as if .bind(this) was used.
     getColor = (row: Row) => {
        return this.fancyColorService.getUserFavoriteColor(row);
     }
    
    }
    
    @Component({...})
    export class TableComponent{
      // This will be bound to the ParentComponent.getColor. 
      // I found this way of declaration a bit safer and convenient than just raw Function declaration
      @Input('getRowColor') getRowColor: (row: Row) => Color;
    
      renderRow(){
        ....
        // Notice that `getRowColor` function holds parent's context because of a fat arrow function used in the parent
        const color = this.getRowColor(row);
        renderRow(row, color);
      }
    }
    

    So, I wanted to demonstrate 2 things here:

    1. Fat arrow (=>) functions instead of .bind(this) to hold the right context;
    2. Typesafe declaration of a callback function in the child component.

提交回复
热议问题