Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryList of inherited components in Angular

Tags:

angular

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.

like image 442
AngularChan Avatar asked Dec 13 '22 17:12

AngularChan


1 Answers

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:

  • What are all the valid selectors for ViewChild and ContentChild?
like image 192
yurzui Avatar answered Dec 26 '22 22:12

yurzui