kittencup / angular2-ama-cn

angular2 随便问
691 stars 101 forks source link

Angular 2如何获得某个组件的属性(非父子关系的组件之间) #74

Open natsu12 opened 8 years ago

natsu12 commented 8 years ago

按照NG2官网上的教程做的,点击了一个hero的名字之后,显示对应的hero的detail,HeroListComponent在点击了hero list的某一项之后会改变它的selectedHero属性。现在问题是负责显示detail的HeroDetailComponent怎样拿到这个属性。 官网教程的做法是直接将点击的逻辑放在AppComponent里,通过input的方式将selectedHero属性传给子component——HeroDetailComponent,但我将负责显示hero list 的部分独立出来作为HeroListComponent,有一个类似的issue #23 ,但是解答都是父子组件之间的数据共享,而我这里HeroListComponent和HeroDetailComponent并不是父子关系而是同级的组件,请问这样应该如何获得同级组件的属性呢?

import {Component} from 'angular2/core';
import {HeroDetailComponent} from './hero-detail.component';
import {HeroListComponent} from './hero-list.component';

@Component({
    selector: 'my-app',
    directives: [HeroDetailComponent, HeroListComponent], 
    templateUrl: 'app/template/app.html'
})
export class AppComponent {}
// app.html
<hero-list></hero-list>
<hero-detail></hero-detail>
// hero-list.component
import {Component, OnInit} from 'angular2/core';
import {Hero} from '../interface/hero';
import {HeroService} from '../service/hero.service';

@Component({
    selector: 'hero-list',
    providers: [HeroService], 
    templateUrl: 'app/template/hero-list.html',
    styleUrls: ['app/css/hero-list.css']
})
export class HeroListComponent implements OnInit {
    constructor(private _heroService: HeroService) { }

    public heroes: Hero[];
    public selectedHero: Hero;

    getHeroes() {
        this._heroService.getHeroes().then(heroes => this.heroes = heroes);
    }
    onSelect(hero: Hero) {
        this.selectedHero = hero;
    }

    ngOnInit() {
        this.getHeroes();
    }
}
// hero-detail.component
import {Host, Component, Inject, forwardRef} from 'angular2/core';
import {Hero} from '../interface/hero';
import {HeroListComponent} from './hero-list.component';

@Component({
  selector: 'hero-detail',
  templateUrl: 'app/template/hero-detail.html'
})
export class HeroDetailComponent {
  public hero: Hero;
  // 应该如何获取HeroListComponent中的selectedHero属性
}
kittencup commented 8 years ago

这个和父子没什么区别吧。。写个用service的

import {Component,Inject} from 'angular2/core';

class Service {
    name:number;
}

@Component({
    selector: 'child-a',
    template: `
        <h2>childA</h2>
    `,
})
export class ChildA {

    public _name:number = 0;

    constructor(public service:Service) {
        let i = 0;
        setInterval(()=> {
            this.name = ++i;
        }, 1000);
    }

    set name(value:number) {
        this.service.name = value;
        this._name = value;
    }
}

@Component({
    selector: 'child-b',
    template: `
        <h2>childB</h2>
        {{service.name}}
    `,
})
export class ChildB {

    constructor(public service:Service) {

    }
}

@Component({
    selector: 'app',
    providers: [Service],
    directives: [ChildA, ChildB],
    template: `
       <h1>app</h1>
       <child-a></child-a>
       <child-b></child-b>
    `,
})
export class App {

}