What is @ViewChild in Angular?

import { ViewChild } from @angular/core;
import {
AfterViewInit,
ChangeDetectorRef,
Component,
ElementRef,
ViewChild
} from "@angular/core";
import { HelloComponent } from "./hello.component";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
@ViewChild(HelloComponent) helloComponent: HelloComponent;@ViewChild("domContent") domContent: ElementRef;name: string = "";constructor(private cdRef: ChangeDetectorRef) {}// set name property of child component from parent component
setName() {
this.helloComponent.name = this.name;
}
// set styles attribute of dom element inside parent component
setColor() {
let styles = this.domContent.nativeElement.getAttribute("style");
const colors = ["red", "green", "blue"];
styles = `${styles} color:${
colors[Math.floor(Math.random() * colors.length)]
};`;
this.domContent.nativeElement.setAttribute("style", styles);
}
// set name property to default value after view initialization
ngAfterViewInit() {
this.helloComponent.name = "World";
this.cdRef.detectChanges();
}
}
<!--child component-->
<hello></hello>
<p #domContent style="display:inline;">Modifying DOM element</p>
<button style="margin-left:20px; width:120px;" (click)="setColor()">Change color</button>
<div style="margin-top:20px;">
<label>Enter your name:</label>
<br>
<div style="margin-top:5px;">
<input type="text" [(ngModel)]="name">
<button style="margin-left:10px; width:120px;" (click)="setName()">Change name</button>
<small *ngIf="!name.length" style="color:red;display:block;margin-top:5px;">Name is required</small>
</div>
</div>
import { Component } from "@angular/core";@Component({
selector: "hello",
template: `
<h1>Hello {{ name }}!</h1>
`,
styles: [
`
h1 {
font-family: Lato;
}
`
]
})
export class HelloComponent {
name = "World";
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store