角度访问嵌套级别的组件

时间:2018-01-25 21:29:41

标签: angular

我有一个父组件。其中可能包含许多组件。那些所有组件可能都有一个我感兴趣的特殊组件。

ParentComponent
     SubComponent1
           MySpecialComponent
      SubComponent2
           MySpecialCompoent
      SubComponent3
           SubSubComponent31
                MySpecialCompnoent     

我正在寻找从ParentComponent获取MySpecialCompnoent实例的方法。 @viewChildren会工作吗? MySpecialCompnoent永远不会直接包含在parentcompoent中。它可能低于许多级别。 我尝试使用@viewchildren访问;但我得到一个空数组而不是

1 个答案:

答案 0 :(得分:0)

我建议使用一种服务来在不直接相关的组件之间中继消息 - 无论如何,也许如果/当你对Angular基础知识更加流畅时,可以使用像NgRX这样的状态管理状态管理。

有很多方法可以做到这一点,但有一种可能是:

<强> service.ts

@Injectable()
export class CommsService {
    somethingHappens:EventEmitter<any> = new EventEmitter();
}

<强> component1.ts

constructor(private comms: CommsService) {}
doSomething() {
    this.comms.somethingHappens.emit({
       oops: 'I accidentally a whole bottle'
    });
}

<强> component2.ts

constructor(private comms: CommsService) {}
private subs:Subscription[];
ngOnInit() {
    this.subs = [
        this.comms.somethingHappens.subscribe(whatHappens => {
            this.doSomethingWithTheInfo(whatHappens);
            console.log(whatHappens.oops); // I accidentally a whole bottle
        });
    ];
}

ngOnDestroy() {
    // No memory leaks, please
    this.subs.forEach(subscription => subscription.unsubscribe());
}