angular使用class-interface获取父组件和祖先组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zgrbsbf/article/details/81911917

在angular中,并没有现成的方法获取父组件,但是: because every component instance is added to an injector’s container, you can use Angular dependency injection to reach a parent component.
那么,如果父组件能在依赖注入中把自己当作一个服务注入,后代就能访问到这个依赖,这样后代组件就可以通过依赖注入访问到这个父组件了。
AComponent是爷组件,BComponent是父组件,CComponent是子组件。想在后代组件中访问祖先。
把A组件注入给自己

@Component({
  selector: 'a-com',
  template: '----我是a组件,<b-com></b-com>',
  providers: [{provide: Parent, useExisting: AComponent}]
})
export class AComponent implements AfterViewInit {
  name = '(a)';

  @ViewChild(BComponent) b: BComponent;

  constructor() {
  }

  ngAfterViewInit() {
    console.group();
    console.log('A中调b:');
    this.b.sayName();
    console.groupEnd();
    console.group();
    console.log('A中调c:');
    this.b.c.sayName();
    console.groupEnd();
  }
  sayName() {
  }
}

在A组件中使用了一个别名提供商,useExisting,其作用是把一个令牌映射到另一个令牌上,创造了访问同一个服务对象的两种方法

@Component({
  selector: 'b-com',
  template: '----我是b组件,父组件是{{parent.name}}<c-com></c-com>---',
  providers: [{provide: Parent, useExisting: BComponent}]

})
export class BComponent implements AfterViewInit {
  name = '(b)';
  @ViewChild(CComponent) c: CComponent;

  constructor(@SkipSelf() public parent: Parent) {
    console.log('b组件找到的爸爸是', parent.name);
  }

  ngAfterViewInit() {
    this.c.sayName();
  }

  sayName() {
    console.log('我是b');
  }
}

B组件的构造函数中注入Parent的时候使用了SkipSelf装饰器,否则的话会报错如下:
这里写图片描述
这是一个循环依赖错误,自己使用自己了。
C组件如下:

@Component({
  selector: 'c-com',
  template: `----我是c,父组件是{{parent.name}},
  <button (click)="onClick($event)">点我</button>
  `,
})
export class CComponent {

  constructor(@Optional() public parent: Parent) {
    console.log('c组件找到的爸爸是', parent.name);
  }

  onClick() {
    console.log('点我:::', this.parent.name);
  }

  sayName() {
    console.log('我是c');
  }
}

这里写图片描述

那么如果希望在C中访问A该怎么办呢?B中不注入自己就可以了:
这里写图片描述

Parent是这样的哦:

export abstract class Parent {
  name: string;
}

参考文献:
https://angular.cn/guide/dependency-injection-in-action#known-parent

猜你喜欢

转载自blog.csdn.net/zgrbsbf/article/details/81911917