Declares a reference to multiple child elements.

The list is automatically updated when the DOM is updated.

The ViewChildren annotation takes an argument that specifies the elements to be selected.

  • If the argument is a Type, directives or components with the type will be bound.
  • If the argument is a String, the string is interpreted as a list of comma-separated selectors. For each selector, an element containing the matching template variable (e.g. #child) will be bound.

View children are set before the ngAfterViewInit callback is called.

Example

With type selector:

@Component(
  selector: 'child-cmp',
  template: '<p>child</p>'
)
class ChildCmp {
  doSomething() {}
}

@Component(
  selector: 'some-cmp',
  template: '''
    <child-cmp></child-cmp>
    <child-cmp></child-cmp>
    <child-cmp></child-cmp>
  ''',
  directives: const [ChildCmp]
)
class SomeCmp implements AfterViewInit {
  @ViewChildren(ChildCmp)
  QueryList<ChildCmp> children;

  @override
  ngAfterViewInit() {
    // children are set
    for ( var child in children ) {
      child.doSomething();
    }
  }
}

With string selector:

@Component(
  selector: 'child-cmp',
  template: '<p>child</p>')
class ChildCmp {
  doSomething() {}
}

@Component(
  selector: 'some-cmp',
  template: '''
    <child-cmp #child1></child-cmp>
    <child-cmp #child2></child-cmp>
    <child-cmp #child3></child-cmp>
  ''',
  directives: const [ChildCmp])
class SomeCmp implements AfterViewInit {
  @ViewChildren('child1, child2, child3')
  QueryList<ChildCmp> children;

  @override
  ngAfterViewInit() {
    // children are set
    for ( var child in children ) {
      child.doSomething();
    }
  }
}
Inheritance
  • Object
  • ViewChildren

Constructors

ViewChildren(Object selector, { Object read })
const

Properties

descendants → bool
Whether to query only direct children (false) or all children (true).
final, inherited
first → bool
Whether to only query the first child.
final, inherited
hashCode → int
The hash code for this object. [...]
read-only, inherited
read → Object
The DI token to read from an element that matches the selector.
final, inherited
runtimeType → Type
A representation of the runtime type of the object.
read-only, inherited
selector → Object
Either the class Type or selector String.
final, inherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a non-existent method or property is accessed. [...]
inherited
toString() → String
Returns a string representation of this object.
inherited

Operators

operator ==(other) → bool
The equality operator. [...]
inherited