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.

How to update Angular 11

How to update Angular 11

Updating Angular projects on a regular basis is very important. This article covers how to update Angular to version 11 from version 7. It also provides information about new features on Angular 11.

How to compile Angular into single bundle.

How to compile Angular into single bundle.

Steps to compile an Angular application into a single bundle. An overview of the types of Angular compilation bundles and ways to cache bust an Angular application.

Create Angular Component after Application Initializes

Create Angular Component after Application Initializes

Basic learning of how to use build-in tools provided by Angular in order to create components after an application has been loaded.

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