publication

Angular: ViewChild and Local References

Miquel Canal

Tuesday 13, September 2016
  • Angular

The viewChild is a decorator used by Angular to access the first element of a matched selector. This can be used to reference a certain element inside a component’s template.

To place a Template Reference Variables (also known as local references) in an element the #ref-name form should be used. The viewChild will search for matches across the local references placed on a template. An example of direct access to a DOM element using viewChild and local references:

Template

<div>
    <span #item> Text of the span </span>
<div>

Component

export class AppComponent implements AfterViewInit {
    // Get the DOM element
    @ViewChild( 'item', { read: ElementRef } )
    private element: ElementRef;

    ngAfterViewInit() {
        // Access the innerHTML property of the nativeElement
        console.log( this.element.nativeElement.innerHTML );
    }
}

nativeElement warnings

For any component used inside an application, Angular compiles it and generate a factory view for all its properties. The DOM elements are a representation of the properties contained under that factory view. Any changes or removals applied directly into a DOM element will not have an effect on the factory view thus creating a void gap on the internal template-view relation.

That is one reason why accessing the DOM elements directly is discouraged by Angular. Another reason is that there are platforms, such as servers or web workers, that do not support native access to the elements and create rendering errors.

The alternatives that Angular offers to access the values and properties of an element are to either implement templating and data-binding or use their native API under the Renderer 2 class.

TypeScript Models

TypeScript Models

Basic overview of the TypeScript and ECMAScript 6 models. An example of use case to exemplify the use of models in external classes.

Angular: Data Binding

Angular: Data Binding

Data communication between the logic component and DOM elements of an Angular application.

Angular: Routing

Angular: Routing

Understand the basics of Angular routing and review core concepts and internal architecture.

This site uses cookies to ensure a great experience. By continue navigating through the site you accept the storage of these cookies.