When you want to control a child component, directive or DOM element from its parent component, you can use the Viewchild decorator in Angular. Viewchild returns the first element that matches a give child component, directive or DOM element and updates it if the reference changes dynamically. In the case you need to control multiple child components use ViewChildren instead.

You can also take a look at the docs on Angular viewchild.

Child Component

Let’s say we have a child component with a function play() on it. This becomes available in the parent as follows:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

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

  ngAfterViewInit() {
    console.log(this.child.play());
  }
}

Note that we use the AfterViewInit lifecycle hook for then child components and directives become available.

Directive

Let’s say we have a directive to upgrade the generation of a grandparent.

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

@Directive({ selector: '[appGreat]' })
export class GreatDirective {
  otherPrefix = 'second';

  constructor(elem: ElementRef, renderer: Renderer2) {
    let greatPrefix = renderer.createText('great ');
    renderer.appendChild(elem.nativeElement, greatPrefix);
  }
}

That we use like this to up the generation by one.

<span appGreat>grandfather</span> // great grandfather

Then we can the internal properties of the directive by using ViewChild.

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { GreatDirective } from './great.directive'

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
  prefix: string;

  @ViewChild(GreatDirective)
  set appGreat(directive: GreatDirective) {
    this.prefix = directive.otherPrefix;
  };

  ngAfterViewInit() {
    console.log(this.prefix); // second
  }
}

DOM Element

Let’s say we have a DOM element with an easy selector.

<input #nameInput placeholder="Family name">

Then we can control this element by setting its value:

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
  @ViewChild('nameInput') nameInput: ElementRef;

  ngAfterViewInit() {
    this.nameInput.nativeElement.value = "Boland!";
  }
}

So that’s it. We can take control from the parent component of child components, directives and DOM elements. All with the help of Angular Viewchild.