Lestoroer
Lestoroer

Reputation: 531

Why [style] doesn't update

I have this code app.component.ts

ngOnInit() {

      let width600 = this.commonService.width600();
      let width380_768 = this.commonService.width380_768();
      let width768 = this.commonService.width768();
      let width992 = this.commonService.width992();
      let width1200 = this.commonService.width1200();

  function handler(mediaQueryList) {
     if (width380_768.matches) {
        this.maxWidth = 200;
     } 
     if (width768.matches) {
        this.maxWidth = 500;

     } 
     if (width992.matches) {
        this.maxWidth = 800;
     } 
     if (width1200.matches) {
        this.maxWidth = 1000;
     } 
  }

 window.matchMedia('(max-width: 767px), (min-width: 768px) and (max-width: 991px), (min-width: 1200px)').addListener(handler);

}

When width of screen is changed then fired one of instriction if and this.maxWidth is chenged on the another value.

This code app.component.html

<div class="content" [style.maxWidth.px]="maxWidth">
</div>

It doesn't work although maxWidth is changed. I think it doesn't update DOM element what why it doesn't work. I tried to do it with (click) and all works.

Upvotes: 0

Views: 579

Answers (1)

yurzui
yurzui

Reputation: 214017

You can use ChangeDetectionRef to detect changes

import { ChangeDetectorRef } from '@angular/core';

export class AppComponent {
  maxWidth: any = 900;
  constructor(private cd: ChangeDetectorRef) {}

  ngOnInit() {
    window.matchMedia('(max-width: 767px), (min-width: 768px) and (max-width: 991px), (min-width: 1200px)').addListener(this.handler.bind(this));
  }

  handler(mediaQueryList) {
    this.maxWidth = 200;
    this.cd.detectChanges();
  }
}

Plunker Example

or run your handler inside angular2 zone like:

import { Component, NgZone } from '@angular/core';

export class AppComponent {
  maxWidth: any = 900;
  constructor(private ngZone: NgZone) {}

  ngOnInit() {
    window.matchMedia('(max-width: 767px), (min-width: 768px) and (max-width: 991px), (min-width: 1200px)').addListener((mediaQueryList)=>{
       console.log(NgZone.isInAngularZone());
       this.ngZone.run(() => this.handler(mediaQueryList));
    });
  }

  handler(mediaQueryList) {
    this.maxWidth = 200;
  }
}

Plunker Example

Upvotes: 3

Related Questions