angular tutorials

How to select an element in a component template – Angular ?

This tutorial guides you on how to select an element in a component template in Angular using ViewChild and ContentChild decorators.

Select an element in a component template – Angular

You can use the following declarative ways to access or select an element in a component template in Angular application.

1. ViewChild

It is an angular property that configures a view query. The change detector detects the view DOM changes and when a new child matches the selector, the property will be updated. The change detector looks for the directive matching the selector in the view DOM.

To fetch local references i.e., template reference variables through ViewChild you can declare angular property of type ElementRef in your component class as shown below.

Syntax

@ViewChild('<local-reference-selector>', {static: true}) <viewchild-property-name>: ElementRef;

Example

 @ViewChild('itemDescInput', {static:true}) itemDescInput: ElementRef;

ElementRef is a wrapper around a native element inside of a View. This ElementRef has the useful property that we can use called nativeElement property. To access the input element value via local references that is fetched through ViewChild you can access in the following way.

this.itemDescInput.nativeElement.value

For example, component template.

<div class="row">
    <div class="col-xs-12">
      ----
      ----
      <label>Item Description</label>     
      <input 
          type="text" 
          class="form-control" 
          #itemDescInput>
      ----
      ----
    </div>
  </div>

Here is how you select an element in a component template. For example, component class.

export class CreateItemComponent implements OnInit {

  -----
  -----

  @ViewChild('itemDescInput', {static:true}) itemDescInput: ElementRef; 

  -----
  -----

  onAddItem(itemNameInput : HTMLInputElement) {        
    this.itemAdded.emit({      
        itemTitle: itemNameInput.value,        
        itemDesc: this.itemDescInput.nativeElement.value
    });
  }

  -----
  -----

}

Please check ViewChild in Angular 9 Example tutorial for complete example. This example demonstrates how to access or select an element in a component template using local references and @ViewChild.

2. ContentChild

It is an angular property that configures a content query. It can be used to get the first element or the directive matching the selector from the content DOM.

Note, content queries are set before the ngAfterContentInit() callback is called.

Please check Program to select an element with @ContentChild – Example. In this example, you will learn how to use the template reference variable “#contentParagraph” to access ng-content using @ContentChild within Angular component.

App Component Template

<div class="container">
  -----
  -----
  <div class="row">
    <div class="col-xs-12">
      ------
      ------
      <app-item-element *ngFor="let elem of itemElems"
                        [itemElem] = "elem"
                        [title] = "elem.title">
                        <!-- Projecting content into component with ng-content -->
                        <p #contentParagraph>
                          <strong *ngIf="elem.type === 'item'" style="color: orange">{{ elem.desc }}</strong>
                          <em *ngIf="elem.type === 'spec'">{{ elem.spec }}</em>
                        </p>
      </app-item-element>                   
    </div>
  </div>
</div>

For example, you can access ng-content using @ContentChild in the following way.

export class ItemElementComponent implements OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy{
  -----
  -----
  @ViewChild('heading', {static: true}) header : ElementRef;
  @ContentChild('contentParagraph', {static: true}) paragraph : ElementRef;
  
  -----
  -----

  ngOnInit(): void {
    console.log("ngOnInit called.....");
    console.log('Header Content:' + this.header.nativeElement.textContent);
    console.log('Paragraph text Content:' + this.paragraph.nativeElement.textContent);
  }

  -----

  ngAfterContentInit(){
    console.log("ngAfterContentInit called.....");
    console.log('Paragraph text Content:' + this.paragraph.nativeElement.textContent);
  }

  -----
  -----

}

That’s it. You had learnt how to access or select an element in a component template using ViewChild and ContentChild parameter decorators in Angular.

Hope it helped 🙂

References:

guest
0 Comments
Inline Feedbacks
View all comments