1

I can access components in a component view using @ViewChildren decorator like this:

@Component({
  selector: 'my-app',
  template: `
    <alert type="info"></alert>
  `,
})
export class App {
  @ViewChildren(AlertComponent) alerts: QueryList<AlertComponent>

Is there any way to access DOM elements with @ViewChildren decorator other then using # symbol in a template? Maybe some kind of read parameter flavor?

  selector: 'my-app',
  template: `
    <div #divElement>Tada!</div>
  `,
})

@ViewChild("divElement") div: any;

If not possible, please mention that in comments or an answer. Just want to know for sure.

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

2

The ViewChild decorator works only with ComponentRef or ref-variable. The second parameter works against the already queried element. A pretty good answer is given here:

https://stackoverflow.com/a/35209681/324224

How the ViewChild is implemented can be seen in the Angular repo:

https://github.com/vicb/angular/blob/master/modules/@angular/core/src/metadata/di.ts#L353

And based on the documentation and the tests:

https://github.com/angular/angular/blob/14ee75924b6ae770115f7f260d720efa8bfb576a/modules/%40angular/core/test/metadata/di_spec.ts

I am pretty sure that only two selector types are supported - ComponentRef and ref-variable.

Community
  • 1
  • 1
George K
  • 1,763
  • 1
  • 9
  • 17
  • thanks, but the question is specific to accessing them _using `@ViewChildren`_, as I stated in my question. This is specifically to not break level of abstraction. I'll upvote anyways – Max Koretskyi Feb 09 '17 at 08:06
  • thanks, it'd be great to see the implementation of querying process – Max Koretskyi Feb 09 '17 at 08:39
  • I could be mistaken, but I think this is the query code : https://github.com/angular/angular/blob/master/modules/%40angular/compiler/src/view_compiler/query_binder.ts#L18 – George K Feb 14 '17 at 08:43