4

i have the following components: Base component A. Components B and C are inherited from 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 {}

And there is a component class which contains all of the A, B and C components:

<A></A>
<B></B>
<C></C>

My question is how can i get the querylist of all A, B and C?

I've tried

@ViewChildren(A) components: QueryList<A>;

but it gives me only A component.

Here's also plunkr that demonstrates the issue.

Thank you in advance.

yurzui
  • 205,937
  • 32
  • 433
  • 399
AngularChan
  • 135
  • 2
  • 11

1 Answers1

14

In order to get all components throught @ViewChildren(A) query you should define A provider on each of your derived components:

@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 {}

Later in your parent component you should write something like:

@ViewChildren(A) components: QueryList<A>;

Ng-run Example

See also:

yurzui
  • 205,937
  • 32
  • 433
  • 399