How can I export a function from one component to another? ANGULAR 2/4

2

Good stackeros!,

I have learned to use the Output () / Input () in Angular 2/4, and while practicing, it has given me the chance that I needed to export (Output) a function I had already created in one component, and import it (Input) to another. Do you know any way to do it ?, I've been looking for it but I can not find anything, or I do not know very well.

Thanks for the help people!

    
asked by PictorGames 12.08.2017 в 14:15
source

1 answer

2
  

From component A, having component B as a child you send your variable Output() myOutput to its variable Input() myInput .

@Component({
  selector: 'app-a-component',
  template: '
    Hello from AComponent
    <app-component-b></app-component-b>
  '
})
export class AComponent implements OnInit {

  @Output() myOutput = new EventEmitter<any>();
  @ViewChild(BComponent) bComponent: BComponent;

  constructor() {}

  ngOnInit() {
    this.bComponent.myInput = this.myOutput;
  }

}
  

From component B, you are listening for changes in the Input() until you receive a new change in your Input() myInput and there you can be sure that they have sent something to that variable, in your case the other variable of component A.

@Component({
  selector: 'app-b-component',
  template: 'Hello from BComponent'
})
export class BComponent implements OnChanges {

  @Input() myInput: EventEmitter<any> | null = null;

  constructor() {}

  ngOnChanges(changes: SimpleChanges) {
    if (changes['myInput']) {
      const myOutputReceived = changes.myInput.currentValue;
      // Aquí estás seguro que has recibido cambios en myInput.
    }
  }

}
    
answered by 12.08.2017 / 14:48
source