Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 使用媒体查询更改元素的类,4_Html_Angular_Typescript - Fatal编程技术网

Html 使用媒体查询更改元素的类,4

Html 使用媒体查询更改元素的类,4,html,angular,typescript,Html,Angular,Typescript,要在浏览器宽度更改时更改元素的类吗 把它放在我的口袋里 matchMedia('(max-width: 400px)').addListener((mql => { if (mql.matches) { this.myclass = 'toggled'; } })); 在html类似的东西中: <app-side-bar [ngClass]="myclass"></app-side-bar> “myclass”的值已更改,但HTML元素(应用程

要在浏览器宽度更改时更改元素的类吗 把它放在我的口袋里

 matchMedia('(max-width: 400px)').addListener((mql => {
  if (mql.matches) {
    this.myclass = 'toggled';
}
}));
在html类似的东西中:

<app-side-bar [ngClass]="myclass"></app-side-bar>


“myclass”的值已更改,但HTML元素(应用程序侧栏)未得到更新-我缺少什么?

因为Angular会跟踪浏览器大小更改时发生的事件,所以它不会检测到更改。你必须自己触发它:

您可以通过在
NgZone
中扭曲代码来完成此操作:

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

// Inject NgZone in your constructor:    
constructor(private zone: NgZone) {

}

// Run the code that changes state inside the zone
matchMedia('(max-width: 400px)').addListener((mql => {
    if (mql.matches) {
        this.zone.run(() => {
            this.myclass = 'toggled';
        });
    }
}));

你真是个该死的英雄,先生-这么多个小时都在想办法,泰!!-所以通过写“this.zone.run”我强迫一个事件正确?对。Angular跟踪在触发更改检测的
区域内执行的代码所做的更改。