|
| 1 | +# Resize observer |
| 2 | + |
| 3 | +The resize observer allows to react on element's size changes triggered by user interaction. |
| 4 | + |
| 5 | +## Usage --- |
| 6 | + |
| 7 | +## When to use |
| 8 | + |
| 9 | +- Adapt an element's layout based on its own size, not just the viewport. |
| 10 | + For example, changing styles for a specific sidebar when its container is resized. |
| 11 | +- When model changes are required or an adjustment via javascript is necessary. |
| 12 | + |
| 13 | +## When not to use |
| 14 | + |
| 15 | +Prefer a pure CSS solution e.g.: |
| 16 | + |
| 17 | +- **Viewport-based responsiveness** CSS media queries provide a powerful alternative and the element CSS utils allow to apply different behaviors based on [breakpoints](../fundamentals/layouts/breakpoints.md). |
| 18 | +- **Container-based responsiveness** [CSS container queries](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_containment/Container_queries) provide powerful alternative to build responsive layouts. |
| 19 | + |
| 20 | +## Code --- |
| 21 | + |
| 22 | +The resize observer can be integrated into your application using either a service or a directive, depending on your requirements: |
| 23 | + |
| 24 | +- **Service approach:** Use the `ResizeObserverService` to programmatically observe size changes on any element. This is useful when you need fine-grained control or want to react to changes in code. |
| 25 | +- **Directive approach:** Apply the `SiResizeObserverDirective` directly in your template to handle resize events declaratively. This is ideal for simple use cases where you want to bind resize logic directly to your component's view. |
| 26 | + |
| 27 | +Choose the method that best fits your application's architecture and complexity. |
| 28 | + |
| 29 | +**Use resize observer service:** |
| 30 | + |
| 31 | +```ts |
| 32 | +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; |
| 33 | +import { ResizeObserverService } from '@siemens/element-ng/resize-observer'; |
| 34 | + |
| 35 | +inject(ResizeObserverService) |
| 36 | + .observe(inject(ElementRef<HTMLElement>).nativeElement, 100) |
| 37 | + .pipe(takeUntilDestroyed()) |
| 38 | + .subscribe(event => {/* Handle size change */}) |
| 39 | +``` |
| 40 | + |
| 41 | +**Use resize observer directive:** |
| 42 | + |
| 43 | +```ts |
| 44 | +import { Component } from '@angular/core'; |
| 45 | +import { SiResizeObserverDirective } from '@siemens/element-ng/resize-observer'; |
| 46 | + |
| 47 | +@Component({ |
| 48 | + selector: 'sample', |
| 49 | + imports: [SiResizeObserverDirective], |
| 50 | + template: `<div (siResizeObserver)="resize($event)"></div>` |
| 51 | +}) |
| 52 | +export class SampleComponent { |
| 53 | + resize(e: any): void { |
| 54 | + // Handle size changes |
| 55 | + } |
| 56 | +} |
| 57 | +``` |
0 commit comments