[Angular 2] @ViewChild to access Child component's method

时间:2021-12-27 09:11:56

When you want to access child component's method, you can use @ViewChild in the parent:

Parent Component:

import {Component, OnInit, ViewChild} from 'angular2/core';
import {HeroService, Hero} from './HeroService';
import {Observable} from 'rxjs/Rx';
import {SelectedHero} from './selected-hero';
import {HeroItem} from './hero-item';
@Component({
selector: 'hero-list',
directives: [SelectedHero, HeroItem],
template: `
<button (click)="removeSelectedHero()">clear</button>
<ul>
<li *ngFor="#hero of heros | async">
<hero-item [hero]="hero" (changed)="thisHero = $event"></hero-item>
</li>
</ul>
<selected-hero [thisHero]="thisHero"></selected-hero>
`
}) export class HeroList implements OnInit{ heros: Observable<Hero[]>;
@ViewChild(SelectedHero) selectedItem: SelectedHero; constructor(public heroService: HeroService){} ngOnInit(){
this.getHeros();
} removeSelectedHero(){
this.selectedItem.clear();
} getHeros(){
this.heros = this.heroService.getHeros();
}
}

Child Component:

import {Component, Input} from 'angular2/core';
import {Hero} from './HeroService';
@Component({
selector: 'selected-hero',
template: `
<h2>{{thisHero && thisHero.name}}</h2>
`
}) export class SelectedHero{ @Input() thisHero: Hero;
constructor(){ } clear(){
this.thisHero = new Hero("");
}
}