首页 > 数据库技术 > 详细

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

时间:2016-04-05 01:58:05      阅读:410      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!