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

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Angular 2] @ViewChild to access Child component's method相关的知识,希望对你有一定的参考价值。

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("");
    }
}

 

以上是关于[Angular 2] @ViewChild to access Child component's method的主要内容,如果未能解决你的问题,请参考以下文章

Angular 2+:获取@ViewChild() 的子元素

Angular 2 @ViewChild 返回未定义

如何在 Angular 中使用多个 ViewChild 元素 (2/4)

Angular Viewchild undefined

Angular 在项目中学习@ViewChild和ElementRef的使用

错误 TS2554:预期 2 个参数,但使用 @ViewChild 得到 1 个