Sunday, November 25, 2018

Angular – ViewChild Decorator

The ViewChild decorator in Angular is used to query DOM elements in a Template or Directive or a Child component.

Accessing DOM elements can be done by adding a #reference to the element in the template and by using the ViewChild decorator in the component to get a handle to the element. The reference to the element will be available in the component only after the view initialization is completed, hence we can use this handle in the ngAfterViewInit lifecycle hook.

The following sample adds a reference #refInput to the template, and uses the reference to access the DOM element in the component.
<input refinput="" type="test" />

export class AppComponent implements AfterViewInit {
  @ViewChild('refInput') refInput: ElementRef;
  ngAfterViewInit() {
    this.someInput.nativeElement.value = "Hello Ref";
  }
}

Getting handle to a directive used in the component is also similar, instead of the ref name we will have to import the directive and use the directive object to get the handle as follows. In the following sample we will get a reference to the myDirective

import { myDirective } from './bacon.directive'
export class AppComponent {
  @ViewChild(myDirective)
}

Finally to get handle of a child component we will have to import the child component and use the child component object to get the handle as follows.

import { ChildComponent } from './child.component';
export class AppComponent implements AfterViewInit {
  @ViewChild(ChildComponent) child: ChildComponent;
}


Search Flipkart Products:
Flipkart.com

No comments: