How to get the height of sibling div and send data to sibling component in Angular?
In this post we will see how we can fetch the height of dynamic div in one component and send it to its sibling component in Angular. This task needs an understanding of some basic angular and DOM concepts. In angular, we can send and receive data to siblings using many methods and one of them is through the parent. See the figure below.
In Angular we can perform these steps:
- Create an EventEmitter<T> object and send data to parent using @Output() decorator.
- Receive data from parent using @Input() decorator.
- Calculate the height of div using offsetHeight property of DOM and send it back to parent.
- Receive the height from parent.
Let’s demonstrate these steps using a simple example. We will create two components : sibling1 and sibling2. In sibling1, we will take comma-separated input from user and use it to dynamically populate sibling2. The sibling2 component will dynamically send back its height to sibling1 through the parent.
Prerequisites: NPM must be installed.
Install Angular and create a new project.
npm install -g @angular/cli ng new <project-name> cd <project-name>
Create 2 new components named sibling1 and sibling2, this will create two new directories with 4 files in each.
ng g c sibling1 ng g c sibling2
In the above code, we have set the height variable as input to this component using @Input() decorator. The emitter object is an EventEmitter object. In send() method, we are using value of target element and emitting the data.
There is a input field that uses send() method on keyup event. To show the height variable, we have used a <p> tag.
In this file, we have set the data variable as input and emitter object to emit the height. In send() method, we have emitted the height of div component. Now add the following code to sibling2.component.html:
Here we have used the DOMCharacterDataModified event to detect change in div on insertion of new data. The elements in data array are displayed in the inner <p> tag.
Now we have to add these components to app component. Add the following code to app.component.ts to create variables to transfer data among siblings:
The height and data variables will be used as input to components. The mergeData() and mergeHeight() methods will set the data to these variables. Now display these components in app.component.html :
Now run the app using:
ng serve -o
Output: You should see the following output.
Note that the data sent to other component is used to dynamically increase or decrease the height of div that is being sent to the sibling component.