Angular2 passing function as component input is not working

后端 未结 2 1154
南笙
南笙 2021-01-02 03:42

I\'ve a component that takes function as input. I\'ve passed this function from parent.

Though the function is called, the function is not able to access the depende

相关标签:
2条回答
  • 2021-01-02 03:55

    You need to .bind(this) if you pass methods around:

    <custom-element [valFn]="customVal.bind(this)"></custom-element>
    

    or

    export class App {
      constructor(private service: CustomService) {
      }
      customVal(): string {
        return this.service.getVal();
      }
      customValFn = this.customVal.bind(this);
    }
    

    with

    <custom-element [valFn]="customValFn"></custom-element>
    
    0 讨论(0)
  • 2021-01-02 04:05

    You can pass a get/set property instead of a function in a similar way like that:

    Somewhere in your view:

    <input type="text" [(ngModel)]="yourprop">
    

    In your component file:

    @Component({
      selector: 'myapp',
      templateUrl: './myapp.component.html',
      styleUrls: ['./myapp.component.scss']
    })
    export class App {
      constructor() { }
    
      yourprop: any;
    
      get yourprop(): any {
        return this.scheduleEndDate;
      };
    
      //set accessor including call the onchange callback
      set yourprop(v: any) {
        // TODO do something else
        // You can do whatever you want just like you have passed a function
    
        if (v !== this.scheduleEndDate) {
          this.scheduleEndDate = v;
        }
      }
    
    }
    

    more info @ https://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel

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