Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
How to observe when a element size changes in Angular 2

What is the best way to do some action when the div in the template changes size? The size of the div changes when the window is resized. With Rxjs Observable/subscribe or are the some other way?

Template:

<div #eMainFrame class="main-frame">
   ...
</div>

Component:

@Component({
   selector: 'app-box',
   templateUrl: './box.component.html',
   styleUrls: ['./box.component.css']
})
export class BoxComponent implements OnInit {
   @ViewChild('eMainFrame') eMainFrame : ElementRef;

   constructor(){}

   ngOnInit(){
     // This shows the elements current size
     console.log(this.eMainFrame.nativeElement.offsetWidth);
   }
}

Updated component (this example detects when the window size is changed)

constructor(ngZone: NgZone) { 

   window.onresize = (e) => {
     ngZone.run(() => {
       clearTimeout(this.timerWindowResize);
       this.timerWindowResize = setTimeout(this._calculateDivSize, 100);
     });
   }
}

_calculateDivSize(){
   console.log(this.eMainFrame.nativeElement.offsetWidth); 
}

but this gives me an error:

EXCEPTION: Cannot read property 'nativeElement' of undefined

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The browser doesn't provide anything, therefore you need to poll the value

ngDoCheck() is called when Angular runs change detection. I think this is a good place to do the check:

ngDoCheck() {
  console.log(this.eMainFrame.nativeElement.offsetWidth);
}

If you only need to check once after component creation, use

ngAfterContentInit(){
  // This shows the elements current size
  console.log(this.eMainFrame.nativeElement.offsetWidth);
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda