Angular中继承组件的QueryList

Ang*_*han 3 angular

我有以下组件:基本组件A.组件B和C继承自A.

@Component({
  selector: 'A',
  template: `<div>A</div>`
})
export class A {}

@Component({
  selector: 'B',
  template: `<div>B</div>`
})
export class B extends A {}

@Component({
  selector: 'C',
  template: `<div>C</div>`
})
export class C extends A {}
Run Code Online (Sandbox Code Playgroud)

还有一个包含所有A,B和C组件的组件类:

<A></A>
<B></B>
<C></C>
Run Code Online (Sandbox Code Playgroud)

我的问题是如何获得所有A,B和C的查询

我试过了

@ViewChildren(A) components: QueryList<A>;
Run Code Online (Sandbox Code Playgroud)

但它只给我一个A组件.

这里也是一个证明这个问题的plunkr.

先感谢您.

yur*_*zui 10

为了通过@ViewChildren(A)查询获取所有组件,您应该A在每个派生组件上定义提供程序:

@Component({
  selector: 'A',
  template: `<div>A</div>`
})
export class A {}

@Component({
  selector: 'B',
  template: `<div>B</div>`,
  providers: [{ provide: A, useExisting: B }]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
})
export class B extends A {}

@Component({
  selector: 'C',
  template: `<div>C</div>`,
  providers: [{ provide: A, useExisting: C }]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
})
export class C extends A {}
Run Code Online (Sandbox Code Playgroud)

稍后在您的父组件中,您应该写如下:

@ViewChildren(A) components: QueryList<A>;
Run Code Online (Sandbox Code Playgroud)

Ng-run示例

也可以看看:


归档时间:

查看次数:

540 次

最近记录:

7 年,10 月 前