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<
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.
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