Angular viewChild Decorator

viewChild() decorator is used to manipulate DOM elements.

There are some step to define viewChild() decorators.

Suppose, You create a user component through the below command

ng g c user

Add Class into textbox through viewChild() Decorator

Step 1:- Firstly, create the reference variable through #keyword_name, so I have added #uname in the textbox which is in the user.component.html file.

<div class="text-center" role="main">
<h2>View child</h2>
<div class="row col-md-12">
 <div style="text-align: center; width:50%"> 
<label style="margin-right:10px;">User Name</label>
<input type="text" name="user_name" #uname/>
<input type="button" name="submit" value="submit" />

Step 2:-Now, create a property to hold the reference variable into the user.component.ts file and you want to add the class usercls into the user_name textbox and you have to add class into ngAfterViewInit() method.

Note:- Suppose You have to add a property or change the text then You should call into ngAfterViewInit() method.

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

  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss']
export class UserComponent implements OnInit {

  @ViewChild('uname', {static: false})  username:ElementRef;
  constructor() { }

  ngOnInit() {





Step 3:- Now, check the output class name usercls added into user_name textbox.