qkhanhpro
qkhanhpro

Reputation: 5220

Angular: How to change child element height

Currently I have a layout like so

    <parent-comp>
       <child1> </child1>
       <child2> </child2>
    </parent-comp>

Parent component have fixed height ( 1000px ) Child 1 have 2 states: Expanded( 200px ) and Collapsed( 10px ) I would like to use these information to calculate and update child2's height accordingly

I do not want to set child2's height to auto ( I need a specific value since this is the requirement to pass it into another library (the virtual scroll) )

How can I achieve this?

I tried ViewChild + ElementRef to get child component's height from parent component but it seems to cause ExpressionChangedAfterItHasBeenCheckedError when I try to update the child component's height

Should the child component output it's current height to the parent or the parent should read it from it's child?

Upvotes: 2

Views: 4694

Answers (2)

Siddharth Kaushik
Siddharth Kaushik

Reputation: 316

Yes, you're right. You need to Output the value from child to parent and propagate it to desired components and do your calculations. Here's an example. If you want to pass this change of height to Components other than the children then I would suggest you use a SharedService to subscribe and make changes to the value(s). Siblings or not, this way you can share data between multiple components.

If you just want to update the height, using Flexbox or Grids is a better alternative.

Upvotes: 1

Akshay Rajput
Akshay Rajput

Reputation: 2078

instead of doing it the hard way, you can simply use flex-box, which would take care of doing all the calculations for you.

e.g

.parent {
   display:Flex;
   flex-direction:column;
   flex-wrap:wrap;
   height: 1000px;
}

.child1 {
/*  expanded */
  flex: 0 0 20%;
}

.collapsed {
  flex: 0 0 2%;
}

.child2 {
  flex: 1;
}

you can apply collapsed classed dynamically with the help of ngclass, hope this helps.

If you want to learn more about flexbox play these free game at https://flexboxfroggy.com/ Hope this helps.

Upvotes: 4

Related Questions