How can I select an element in a component template?

Forums AngularHow can I select an element in a component template?
Staff asked 3 months ago

Answers (1)

Add Answer
monika gabani Marked As Accepted
Staff answered 3 months ago

To select element follow the step:

  1.  Add template reference variable in component.html file
  2.  Import @ViewChild decorator.
  3.  Use @ViewChild decorator to use template reference variable in the component.
  4.  select the element in ngAfterViewInit method.

In app-test.component.html file add input element with reference variable.

<input #inputElement value=”CodeHubs”>

Now write code in app-test.component.ts file

import { Component, OnInit, ViewChild, ElementRef } from ‘@angular/core’;

selector: ‘app-test’,
templateUrl: ‘./app-test.component.html’,
styleUrls: [‘./app-test.component.scss’]
export class TestComponent implements OnInit {

@ViewChild(‘inputElement’) inputElement:ElementRef;

constructor() { }

ngOnInit() {

ngAfterViewInit() {

It will display value of input element as CodeHubs in console.


Select Categories