Angular CDK 布局 - 如何动态更新 CSS 以响应屏幕尺寸变化?
Angular CDK Layout - How to dynamically update CSS in response to screen-size changes?
我正在设置一个代码来检测当前断点并相应地更新 class。
我已经设法让它根据初始值工作,但是当 window 大小 enlarges/shrinks 时,Html class 没有检测到变化没有我刷新页面。
我认为代码应该是这样的?
示例组件:
export class NavbarComponent implements OnChanges {
htmlStyles: string;
constructor(
private breakpointObserver: BreakpointObserver
) { }
ngOnChanges(): void {
// Called after the constructor, initializing input properties, and the first call to ngOnChanges.
// Add 'implements OnInit' to the class.
this.breakpointObserver.observe([Breakpoints.Handset, Breakpoints.Medium, Breakpoints.Small])
.subscribe((state: BreakpointState) => {
if (state.matches) {
this.htmlStyles = 'dummy1';
} else {
this.htmlStyles = 'dummy2';
}
});
}
}
示例Html:
<div [ngClass]="htmlStyles" style='max-width: fit-content'>
test
</div>
非常感谢任何帮助,谢谢!
对this.breakpointObserver.observe
的调用应该在ngOnInit
中初始化:
import { BreakpointObserver, Breakpoints, BreakpointState } from '@angular/cdk/layout';
import { Component, OnInit } from '@angular/core'
@Component({
selector: 'navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
htmlStyles: string;
constructor(private breakpointObserver: BreakpointObserver) { }
ngOnInit() {
this.breakpointObserver.observe([Breakpoints.Small])
.subscribe((state: BreakpointState) => {
if (state.matches) {
this.htmlStyles = 'dummy1';
} else {
this.htmlStyles = 'dummy2';
}
});
}
}
我正在设置一个代码来检测当前断点并相应地更新 class。
我已经设法让它根据初始值工作,但是当 window 大小 enlarges/shrinks 时,Html class 没有检测到变化没有我刷新页面。
我认为代码应该是这样的?
示例组件:
export class NavbarComponent implements OnChanges {
htmlStyles: string;
constructor(
private breakpointObserver: BreakpointObserver
) { }
ngOnChanges(): void {
// Called after the constructor, initializing input properties, and the first call to ngOnChanges.
// Add 'implements OnInit' to the class.
this.breakpointObserver.observe([Breakpoints.Handset, Breakpoints.Medium, Breakpoints.Small])
.subscribe((state: BreakpointState) => {
if (state.matches) {
this.htmlStyles = 'dummy1';
} else {
this.htmlStyles = 'dummy2';
}
});
}
}
示例Html:
<div [ngClass]="htmlStyles" style='max-width: fit-content'>
test
</div>
非常感谢任何帮助,谢谢!
对this.breakpointObserver.observe
的调用应该在ngOnInit
中初始化:
import { BreakpointObserver, Breakpoints, BreakpointState } from '@angular/cdk/layout';
import { Component, OnInit } from '@angular/core'
@Component({
selector: 'navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
htmlStyles: string;
constructor(private breakpointObserver: BreakpointObserver) { }
ngOnInit() {
this.breakpointObserver.observe([Breakpoints.Small])
.subscribe((state: BreakpointState) => {
if (state.matches) {
this.htmlStyles = 'dummy1';
} else {
this.htmlStyles = 'dummy2';
}
});
}
}