Calling a function in a child Angular2 Component?

前端 未结 2 754
走了就别回头了
走了就别回头了 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:19

    It turns out I can put a local variable on the component and have access to it's public functions. I.e.:

    <search-bar #SearchBar ...></search-bar>
    <button (click)='SearchBar.ClearHistory()' ...></button>
    

    Apparently the local variable binds to the Component and not the DOM like I originally thought it did. I imagine that I have access to all public fields and functions.

    0 讨论(0)
  • 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: `
        <h1>My First Angular 2 App</h1>
        <child></child>
        <button (click)="submit()">Submit</button>
      `,
      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<SearchBar>) {
        this.childcmp = children.first();
      }
    
      (...)
    }
    

    Hope it helps you, Thierry

    0 讨论(0)
提交回复
热议问题