Angular 4 Equal height divs / columns using Renderer2
We can make use of the Renderer2 library in Angular 4 to manipulate DOM elements. For example, we could equalize the heights of 2 divs / columns using Renderer2.
That's all you have to do! Now, both the divs will be the same height once rendered.
Basically, what we're going to do is to obtain references to the DOM elements that we want to manipulate and then change the desired property value using Renderer2.
1. Obtain References to the DOM elements.
In the HTML view, declare the divs as named templates, like so:
<div class="first-div" #first></div>
<div class="second-div" #second></div>
Now, in the component, we can access references(ElementRefs) to them using @ViewChild.
The component code should look like the following:
import {
Component,
OnInit,
ViewChild,
ElementRef
} from "@angular/core";
export class Component implements OnInit {
@ViewChild("first") first;
@ViewChild("second") second;
}
2. Manipulate DOM elements.
We can use the ngAfterViewChecked life cycle hook to get the rendered height of the first div
and then apply it to the second div using it's ElementRef like so:
constructor(
private renderer: Renderer2
) {}
ngAfterViewChecked() {
if (this.first&& this.second) {
var height = `${this.first.nativeElement.offsetHeight}px`;
this.renderer.setStyle(this.second.nativeElement, "height", height);
}
}
Comments
Post a Comment