Calling a function in a child Angular2 Component?

前端 未结 2 759
走了就别回头了
走了就别回头了 2020-12-13 17:30

I have a Component that acts as a Search Bar. It can make api requests and provide the results to the rest of the app through an @Output and EventEmitter<

2条回答
  •  臣服心动
    2020-12-13 18:20

    You need to leverage the @ViewChild decorator to reference the child component from the parent one by injection:

    import { Component, ViewChild } from 'angular2/core';  
    
    (...)
    
    @Component({
      selector: 'my-app',
      template: `
        

    My First Angular 2 App

    `, directives:[App] }) export class AppComponent { @ViewChild(SearchBar) searchBar:SearchBar; (...) someOtherMethod() { this.searchBar.someMethod(); } }

    Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.

    You can notice that the @Query parameter decorator could also be used:

    export class AppComponent { 
      constructor(@Query(SearchBar) children:QueryList) {
        this.childcmp = children.first();
      }
    
      (...)
    }
    

    Hope it helps you, Thierry

提交回复
热议问题