码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2016-04-05 02:00:05      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5353556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!