How to return a value from an EventEmitter function?

后端 未结 2 1548
时光说笑
时光说笑 2020-12-13 05:37

I got this function in my core component:

 isValid(value: any) {

   // Do some stuff and return somethin         


        
相关标签:
2条回答
  • 2020-12-13 06:35

    The short answer is you can't do this with @Output, but you can do something very similar with @Input.

    Same function in core component:

    isValid(value: any): boolean {
      // Do some stuff and return something based on the result
      return false;
    }
    

    Pass the function definition in to other-component as an @Input:

    <other-component [onBeforeAddingProcessor]="isValid"></other-component>
    

    In other-component:

    @Input() onBeforeAddingProcessor: (value: any) => boolean;
    
    ngOnInit() {
      // onBeforeAddingProcessor won't be defined in the constructor
      let isValid = this.onBeforeAddingProcessor(value);
    
      if (isValid) {
        // Do stuff
      }
    }
    

    Methods accessing this

    If you have to access this in the function you provide, then it's necessary to pass a method which already has the this-context bound:

    isValid = (value: any) => {
      return this.myService.checkValue(value);
    }
    

    Otherwise Angular calls the method with this of the component, not the consumer of the component. Small hint regarding performance (though not tested): if this method is large and the instance-count of the component is high, then you should factor out the bigger parts of the code to a private member function and call this function from where it was factored out. Reason: Above does not create a function on the prototype of the class, but stamps out a copy of this function for each instance of the component. This can consume a lot of memory which can be avoided easily.

    0 讨论(0)
  • 2020-12-13 06:38

    You need to subscribe on the event emitter to get the value:

    this.onBeforeAdding.emit(value || true);
    
    this.onBeforeAdding.subscribe(isValid => {
      if (isValid) {
        // Do stuff
      }
    });
    
    0 讨论(0)
提交回复
热议问题