@ViewChildren decorator in Angular is used to get reference list of elements or directives from the view DOM in a Component class. Using @ViewChildren decorator you can configure a view query, that is done by passing a selector with @ViewChildren. For example
@ViewChildren('uname') userName: QueryList<UserComponent>
Here 'uname' is the passed selector. ViewChildren looks for all the elements or the directives matching the selector in the view DOM and return them as an instance of QueryList which is another class in Angular used to store unmodifiable list of items.
If a child element is added, removed, or moved, the query list will be updated, and the changes function of the QueryList will emit a new value.
Once you have access to DOM elements in the parent Component you can do DOM manipulation.
- View queries and ngAfterViewInit callback
- @ViewChildren Metadata Properties
- Which selectors are supported
- Using ViewChildren with directive
- Using ViewChildren with Component
- Using ViewChildren with ‘read’ property
- Using ViewChildren with template reference variable
- ViewChildren with multiple selectors
- @ViewChildren Vs @ViewChild
View queries and ngAfterViewInit callback
View queries are set before the ngAfterViewInit callback is called. That means ngAfterViewInit callback is the best place to manipulate the element or directive by using the reference variable.
@ViewChildren Metadata Properties
You can pass the following three metadata properties with @ViewChildren decorator.
- selector- The directive type or the name used for querying.
- read- Used to read a different token from the queried elements. It is an optional property.
- emitDistinctChangesOnly- When used the changes method of the QueryList will emit new values only if the QueryList result has changed. Note that this config option is deprecated, right now it is true by default and will be permanently set to true .
Syntax of ViewChildren-
@ViewChildren(selector, { read?: any;})