Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Host Listener Change div heigtht

I read the last couple of hours about Event Listener in Angular 2 but I think there is a big lack of documentation there.

I want to set the height of different div groups (created in ngFor) to the one with the biggest height. Kinda like in Angular 1 example

I know that scope and $watch do not exist anymore. So I try to do it with Host Listener, but I cant find any good documentation for it. There are many tutorials for events "click", "mouseover" etc. But none for other possible events. I need something like $watch or onChange. (No input fields, basic elements) Basiclly any documentation about the possible event names would help.

Eventually there is also an example of the above link in angular2.

PS: Found 'window: resize' but 'div: resize' not working.

EDIT: With the help of maximus I got it done, here is the working code.

Created a directives file:

comments.directive.ts

import { Directive, ElementRef, Input } from '@angular/core';
import { DoCheck } from '@angular/core';

@Directive({ selector: '[comments]' })

export class CommentsDirective implements DoCheck{

    style: any;

    constructor(private element: ElementRef) {

    }

    ngDoCheck() {
        console.log(this.element);
        this.style = { //scope variable style, shared with our controller
            height:this.element.nativeElement.offsetHeight+'px', //set the height in style to our elements height
            width:this.element.nativeElement.offsetWidth+'px' //same with width
        };
    }
}

Than I just imported it in NG-Module.

HTML Part:

<div comments [ngStyle]="style">

If I done the part with making it all equal height, based on the biggest, I will update it.

like image 643
Doomenik Avatar asked Nov 30 '25 01:11

Doomenik


1 Answers

I know that scope and $watch do not exist anymore

Angular.js triggers watchers when it runs digest. Angular has something similar, it triggers ngDoCheck when it runs digest. Read more here.

Taking the analogy with the example you shown for Angular.js you can do something along these lines in Angular:

@Directive({
   selector: '[HeightSetter]'
})
class HeightSetter {
   style: any;

   constructor(private element: elementRef) {

   }

   ngDoCheck() {
     this.style = { //scope variable style, shared with our controller
         height:this.element.nativeElement.offsetHeight+'px', //set the height in style to our elements height
         width:this.element.nativeElement.offsetWidth+'px' //same with width
     };
   }
}

html

<span HeightSetter [ngStyle]="style"></span>
like image 156
Max Koretskyi Avatar answered Dec 01 '25 13:12

Max Koretskyi