Use Angular 4 ViewChild In 5 Minutes

0

Techies, this page will guide you to access your child component, directive or DOM element using Angular 4 ViewChild decorator.

Sometimes, in our angular app, we need to use multiple components at that time we’d require accessing the child component elements.

To do that we need to use Angular 4 ViewChild.

Getting Started With Angular 4 ViewChild

We’re going to see how we can access the Directives, DOM elements and Child components using Angular 4 ViewChild.

The amazing thing is that, if the reference changes dynamically, ViewChild will also update its reference automatically.

1. Access Directives Using Angular 4 ViewChild

First of all, create a directive.

ng g d example

Do you want to learn how to set up Angular 4 app? Take me to Angular 4 Hello World

Here, let’s see ExampleDirective

//Import core modules
import { Directive, ElementRef,  Renderer2} from '@angular/core';

@Directive({
  selector: '[appExample]'
})
export class ExampleDirective {
 	ingredient = 'tomato';

  	constructor(elem: ElementRef, renderer: Renderer2) {
    	let ele = renderer.createText('Coming from Example Directive ==> ');
		renderer.appendChild(elem.nativeElement, ele);
  	}
}

Now, use this directive in our App Component

Here, we’re going to use setter to set the value.

//Import core modules
import { Component, ViewChild, AfterViewInit } from '@angular/core';
//Import directive
import { ExampleDirective } from './example.directive';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
  title = 'app';
  extraIngredient: string;

  @ViewChild(ExampleDirective)
  set appExample(directive: ExampleDirective) {
    this.extraIngredient = directive.ingredient;
  };

  ngAfterViewInit() {
    console.log(this.extraIngredient); // tomato
  }
}

Finally, you can use directive in your App Component HTML like below.

<span appExample>sandwich!</span>

Output will be,

Coming from Example Directive ==> sandwich!

2. Access DOM Element Using Angular 4 ViewChild

Next, we’ll access the DOM element using ViewChild decorator.

Now, have this input in your app component HTML.

<input #pizzaInput placeholder="I like Dominos Pizza">

By using ViewChild, we’ll change the placeholder of this input.

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

import { ExampleDirective } from './example.directive';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
  title = 'app';
  extraIngredient: string;

  /*@ViewChild(ExampleDirective)
  set appExample(directive: ExampleDirective) {
    this.extraIngredient = directive.ingredient;
  };*/
  @ViewChild('pizzaInput') pizzaInput: ElementRef;

  ngAfterViewInit() {
    //console.log(this.extraIngredient); // tomato
    this.pizzaInput.nativeElement.value = "Me too love, 🍕🍕";
  }
}


Here, the text “Me too love, 🍕🍕”, will be replaced in the textbox.

3. Access Child Component Using Angular 4 ViewChild

Let,s create a child component

ng g c child

Now, we’ll create a method in our child component that we’re going to use in app component.

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  whichPizzaYouAre() {
  	return "👶 I am a Domino's pizza from child component!!";
  }

}

Here, in app component, we will access the method of child component using Angular 4 ViewChild.

//Import core
import { Component, ViewChild, AfterViewInit, ElementRef} from '@angular/core';
//Import directive
import { ExampleDirective } from './example.directive';
//Import child component
import { ChildComponent } from './child/child.component';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
  title = 'app';
  extraIngredient: string;

  /*@ViewChild(ExampleDirective)
  set appExample(directive: ExampleDirective) {
    this.extraIngredient = directive.ingredient;
  };*/
  @ViewChild('pizzaInput') pizzaInput: ElementRef;
  @ViewChild(ChildComponent) child: ChildComponent;

  ngAfterViewInit() {
    //console.log(this.extraIngredient); // tomato
    //this.pizzaInput.nativeElement.value = "Me too love, 🍕🍕";
    this.pizzaInput.nativeElement.value = this.child.whichPizzaYouAre(); // 👶 I am a Domino's pizza from child component!!
  }
}


Now, the below HTML will replace the textbox value with “👶 I am a Domino’s pizza from child component!!”

<input #pizzaInput placeholder="I like Dominos Pizza">

Here we go! as you seen that we can access directives, DOM element and child component using Angular 4 ViewChild decorator, it’s easy, right?

Hope, you love this article and stay tuned for further updates.

Moreover, if you want to explore more about Angular 4 ViewChild, visit, Angular ViewChild Document

Furthermore, if you’ve any questions/suggestions, feel free to share your comments below.

Happy Coding!

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of