Angular 2 - How to trigger a method on a child from the parent

前端 未结 2 1186
清酒与你
清酒与你 2020-12-24 10:50

It\'s possible to send data from the parent to a child through @Input, or to call a method on the parent from the child with @Output, but I\'d like to do exactly the other w

相关标签:
2条回答
  • 2020-12-24 11:07

    I think these might be what you're looking for:

    https://angular.io/guide/component-interaction#parent-interacts-with-child-via-local-variable

    https://angular.io/guide/component-interaction#parent-calls-an-viewchild

    You can access child properties and methods using local variables within the template or using the @ViewChild decorator in the parent's component class.

    0 讨论(0)
  • 2020-12-24 11:14

    @ViewChild is the right solution, but the documentation linked above was a bit unclear for me, so I pass a bit more friendly explanation which helped me to understand it.

    Let's have a ChildComponent with a method:

    whoAmI() {
      return 'I am a child!!';
    }
    

    And the parent component, where we can call method above by using '@ViewChild` technique:

    import { Component, ViewChild, OnInit } from '@angular/core';
    
    import { ChildComponent } from './child.component';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    
    export class AppComponent implements OnInit {
    
      @ViewChild(ChildComponent) child: ChildComponent;
    
      ngOnInit() {
        console.log(this.child.whoAmI()); // I am a child!
      }
    }
    
    0 讨论(0)
提交回复
热议问题