Angular

DOM Manipulation Using @ViewChild

Introductions:

First, we need to understand what is DOM and how can we manipulate using a @ViewChild in Angular.

The DOM stands for “Document Object Model”. The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web. In this guide, we’ll briefly introduce the DOM. We’ll look at how the DOM represents an HTML or XML document in memory and how you use APIs to create web content and applications.

Implementations:

In Dom Manipulation we Need Import of “ViewChild” from @angular/core.

import {
  AfterViewInit,
  Component,
  TemplateRef,
  ViewChild,
  ViewContainerRef,
  ViewRef
} from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
  name = "Angular Dom Manipulation";

  @ViewChild("vc", { read: ViewContainerRef }) vc: ViewContainerRef;
  @ViewChild("temp1", { read: TemplateRef }) temp1: TemplateRef<null>;
  @ViewChild("temp2", { read: TemplateRef }) temp2: TemplateRef<null>;
  @ViewChild("temp3", { read: TemplateRef }) temp3: TemplateRef<null>;
  view1: ViewRef;
  view2: ViewRef;
  view3: ViewRef;
  ngAfterViewInit() {
    this.view1 = this.temp1.createEmbeddedView(null);
    this.view2 = this.temp2.createEmbeddedView(null);
    this.view3 = this.temp3.createEmbeddedView(null);
  }

  show(type) {
    let view = this.view1;
    switch (type) {
      case 1:
        view = this.view1;
        break;
      case 2:
        view = this.view2;
        break;
      case 3:
        view = this.view3;
        break;
    }

    this.vc.detach();
    this.vc.insert(view);
  }
}

 

and the Html code will be the like below.

<h2>{{name}}</h2>

<p>
  Click Button and Change Dom
</p>
<button (click)="show(1)">Show Template 1</button>
<button (click)="show(2)">Show Template 2</button>
<button (click)="show(3)">Show Template 3</button>
<div>
  <ng-container #vc></ng-container>
</div>
<div>
  <ng-template #temp1><span class="style1">Dom Element 1</span></ng-template>
  <ng-template #temp2><span class="style2">Dom Element 2</span></ng-template>
  <ng-template #temp3><span class="style3">Dom Element 3</span></ng-template>
</div>

After the successful implementation, our result will be like below

 

Himanshu Kanthariya

Share
Published by
Himanshu Kanthariya

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago