How to apply rendered property of a div or element into another div or element in angular

August 20, 2020 Amrish Kushwaha...
twitterlinkedinreddit
How to apply rendered property of a div or element into another div or element in angular

Problem: how to apply rendered property of a div into another div

Sometimes we want to use the rendered property of an HTML element such as height, width, etc.. to set the property in another HTML element.

Solution: use ngAfterViewChecked lifecycle

This can be easily done in Angular using lifecycle hook ngAfterViewChecked.

Here is the proper solution:

demo.component.html

<div #div1 class="div1">
  <p>Div1</p>
</div>

<div #div2 class="div2">
  <p>Div2</p>
</div>

demo.component.css

.div1 {
  background-color: lightblue;
  height: 100px;
}

@media screen  and (max-width:  767px) {
  .div1 {
    height: 500px;
  }
}

.div2 {
  background-color: lightgreen;
}

demo.component.ts

import { Component, OnInit, ViewChild, Renderer2,AfterViewChecked, HostListener } from '@angular/core';

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css']
})
export class DemoComponent implements OnInit, AfterViewChecked {
  @ViewChild('div1') div1;
  @ViewChild('div2') div2;

  constructor(private renderer: Renderer2) { }

  ngOnInit() {
  }

  @HostListener('window:resize', [])
  onResize() {
    this.setDivHeight();
  }

  ngAfterViewChecked() {
   this.setDivHeight();
  }

  setDivHeight() {
    let height = `${this.div1.nativeElement.offsetHeight}px`;
	  this.renderer.setStyle(this.div2.nativeElement, 'height', height);
  }

}

Working Example

https://stackblitz.com/edit/set-rendered-height-of-div-to-another-div

I hope that you like the article.

Keep coding and keep learning and keep building stuffs...