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.

Angular: Data Binding

Angular: Data Binding

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

Angular Nested Routing

Angular Nested Routing

Angular is one of the most advanced JavaScript frameworks at the moment. Been able to create nested routings based on modules is key to design an easy to scale Angular application.

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.

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