How can I select an element in a component template?

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

Answers (1)

Add Answer
Staff answered 3 years 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’;

@Component({
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() {
console.log(this.inputElement.nativeElement.value);
}
}

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

Subscribe

Select Categories