Getting reference to child component in parent component [duplicate]
You can use ViewChild
<child-tag #varName></child-tag>
@ViewChild('varName') someElement;
ngAfterViewInit() {
someElement...
}
where varName
is a template variable added to the element. Alternatively, you can query by component or directive type.
There are alternatives like ViewChildren
, ContentChild
, ContentChildren
.
@ViewChildren
can also be used in the constructor.
constructor(@ViewChildren('var1,var2,var3') childQuery:QueryList)
The advantage is that the result is available earlier.
See also http://www.bennadel.com/blog/3041-constructor-vs-property-querylist-injection-in-angular-2-beta-8.htm for some advantages/disadvantages of using the constructor or a field.
Note: @Query()
is the deprecated predecessor of @ContentChildren()
- https://github.com/angular/angular/blob/2.0.0-beta.17/modules/angular2/src/core/metadata.dart#L146
- https://github.com/angular/angular/blob/2.0.0-beta.17/modules/angular2/src/core/metadata.dart#L175
Update
Query
is currently just an abstract base class. I haven't found if it is used at all https://github.com/angular/angular/blob/2.1.x/modules/@angular/core/src/metadata/di.ts#L145
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(Child) child:Child;
(...)
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(Child) children:QueryList<Child>) {
this.childcmp = children.first();
}
(...)
}
You may actually go with ViewChild API
...
- Check your forked plunker for complete code - ViewChild API
parent.ts
<button (click)="clicked()">click</button>
export class App {
@ViewChild(Child) vc:Child;
constructor() {
this.name = 'Angular2'
}
func(e) {
console.log(e)
}
clicked(){
this.vc.getName();
}
}
child.ts
export class Child implements OnInit{
onInitialized = new EventEmitter<Child>();
...
...
getName()
{
console.log('called by vc')
console.log(this.name);
}
}