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

后端 未结 10 1525
庸人自扰
庸人自扰 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:38

    UPDATE

    This answer was submitted when Angular 2 was still in alpha and many of the features were unavailable / undocumented. While the below will still work, this method is now entirely outdated. I strongly recommend the accepted answer over the below.

    Original Answer

    Yes in fact it is, however you will want to make sure that it is scoped correctly. For this I've used a property to ensure that this means what I want it to.

    @Component({
      ...
      template: '<child [myCallback]="theBoundCallback"></child>',
      directives: [ChildComponent]
    })
    export class ParentComponent{
      public theBoundCallback: Function;
    
      public ngOnInit(){
        this.theBoundCallback = this.theCallback.bind(this);
      }
    
      public theCallback(){
        ...
      }
    }
    
    @Component({...})
    export class ChildComponent{
      //This will be bound to the ParentComponent.theCallback
      @Input()
      public myCallback: Function; 
      ...
    }
    
    0 讨论(0)
  • 2020-11-27 10:43

    An alternative to the answer SnareChops gave.

    You can use .bind(this) in your template to have the same effect. It may not be as clean but it saves a couple of lines. I'm currently on angular 2.4.0

    @Component({
      ...
      template: '<child [myCallback]="theCallback.bind(this)"></child>',
      directives: [ChildComponent]
    })
    export class ParentComponent {
    
      public theCallback(){
        ...
      }
    }
    
    @Component({...})
    export class ChildComponent{
      //This will be bound to the ParentComponent.theCallback
      @Input()
      public myCallback: Function; 
      ...
    }
    
    0 讨论(0)
  • 2020-11-27 10:47

    Passing method with argument, using .bind inside template

    @Component({
      ...
      template: '<child [action]="foo.bind(this, 'someArgument')"></child>',
      ...
    })
    export class ParentComponent {
      public foo(someParameter: string){
        ...
      }
    }
    
    @Component({...})
    export class ChildComponent{
    
      @Input()
      public action: Function; 
    
      ...
    }
    
    0 讨论(0)
  • 2020-11-27 10:51

    Use Observable pattern. You can put Observable value (not Subject) into Input parameter and manage it from parent component. You do not need callback function.

    See example: https://stackoverflow.com/a/49662611/4604351

    0 讨论(0)
提交回复
热议问题