Using LocalReference with @ViewChild

  • Can be used in place of property binding.
  • Designed to send data between components
  • We can change the DOM data using Element Ref value of ViewChild but it not recommended to use in that way.
  • After Angular8 @ViewChild annotation takes two values.

Changes in app.component.html

    <label>Enter text here</label>
    <input type="text" #textBoxRef>
    <button (click)="onButtonClick()">Click Me</button>
    <p>The text entered in the text box is {{msg}}</p>

Changes in app.component.ts

import { Component, ViewChild, ElementRef } from '@angular/core';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {

  @ViewChild('textBoxRef', {static: true})
  textBoxRef: ElementRef;
  title = 'LocalReferenceDemo';
  msg: string;
    this.msg = this.textBoxRef.nativeElement.value;

Output :

Leave a Comment