Skip to content
Advertisement

Angular Resize Event: prevent user from resizing inner Div outside of parent Div

How to prevent user from resizing inner Div in the demo outside of Outer Div. I am using angular-resize-event.

https://www.npmjs.com/package/angular-resize-event

Stackblitz: https://stackblitz.com/edit/angular-ivy-mcldtj?file=src%2Fapp%2Fapp.component.html

app.component.ts

<div class="parent">
    Outer Div
    <div id="resizableContainer" >
        Inner Div
    </div>
</div>

app.module.ts—–

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AngularResizedEventModule } from 'angular-resize-event';
import { AppComponent } from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.ts

import { Component, VERSION } from "@angular/core";
import { ResizedEvent } from "angular-resize-event";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  public width: number;
  public height: number;
  constructor() {}



  onResized(event) {
    console.log(event)
    this.width = event.newWidth;
    this.height = event.newHeight;
  }
}

style.css—

div#resizableContainer{
  border: 2px solid;
  margin: 20px 0px 20px 0px;
  padding: 20px; 
  width: auto;
  height:300px;
  resize: both; 
  overflow: auto;
}

.parent{
  padding:10px;
  border:2px solid;
}

Thanks

Advertisement

Answer

You just need to specify a max-width on the inner resizable div so the resizing stops at the maximum width specified. You can do this in CSS without the need for any Angular code.

Here is the updated CSS:

div#resizableContainer{
  border: 2px solid;
  margin: 20px 0px 20px 0px;
  padding: 20px; 
  width: auto;
  max-width: calc(100% - 44px);
  height:300px;
  resize: both; 
  overflow: auto;
}

I’m using the calc function to determine the size because you have borders, margins and paddings specified that need to be taken into account when determining the max width. The 44px value is all the borders, margins and paddings summed up. In your StackBlitz sample there is an 8px margin on the body element on both sides so this is 16px. The outer div has a 2px border and 10px margin again on both sides so this is 24px. And last the inner div has a 2px border so you need to add another 4px.

Here is also a link to a fork of your StackBlitz sample where you can see it working.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement