Angular 2+ call a function in a child component from its parent component

前端 未结 3 1625
余生分开走
余生分开走 2020-12-28 12:06

I\'d like to know the best way to do this, and if there are different ways. I\'m trying to call a function in a child component from its parent component. So if I have:

3条回答
  •  隐瞒了意图╮
    2020-12-28 12:39

    Inside of your template, using template variables/references:

    
        
    
    

    live-demo: https://stackblitz.com/edit/angular-so-3?file=src%2Fapp%2Fapp.component.html

    OR

    Inside of your component:

    import { ..., ViewChild, ... } from '@angular/core';
    
    // ...
    
    export class ParentComponent {
       @ViewChild('yourChild' /* #name or Type*/, {static: false}) child;
    
       ngAfterViewInit() {
          console.log('only after THIS EVENT "child" is usable!!');
          this.child.hide();
       }
    }
    

    Inside of your component (option2):

    import { ..., ViewChild, ... } from '@angular/core';
    import { ..., ChildComponent, ... } from '....';
    
    // ...
    
    export class ParentComponent {
       @ViewChild(ChildComponent /* #name or Type*/, {static: false}) child;
    
       ngAfterViewInit() {
          console.log('only after THIS EVENT "child" is usable!!');
          this.child.hide();
       }
    }
    

    See the official docs: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child

提交回复
热议问题