Posted on: February 19, 2023|Amrish Kushwaha

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

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...

About author:

Amrish Kushwaha

Amrish Kushwaha

I am Amrish Kushwaha. Software Engineer, Maker, Writer. I am currently focused on frontend development with curiosity of building end to end software system. Currently I am working at Rafay Systems. I love to write as well as build side projects when I am free.

Related category articles: