自定义Angular CDK布局断点:1600px响应式布局失效求助
解决Angular CDK Layout自定义1600px断点监听失效问题
你的问题出在仅监听了预定义的移动端断点,当窗口宽度在非移动端区间(比如从1500px调整到1700px)时,预定义断点的匹配状态没有变化,所以subscribe回调不会触发,自然无法执行宽屏状态的判断逻辑。
修改方案
把自定义的1600px断点加入breakpointObserver.observe的监听数组,让Angular CDK监听这个断点的状态变化,而非仅在移动端断点变化时才执行判断。
修改后的代码
// 定义自定义断点常量,方便复用和维护 const WIDESCREEN_BREAKPOINT = '(min-width: 1600px)'; this.breakpointObserver.observe([ Breakpoints.Handset, Breakpoints.HandsetLandscape, Breakpoints.HandsetPortrait, WIDESCREEN_BREAKPOINT // 加入自定义断点 ]) .subscribe(result => { this.handsetView = false; this.widescreenView = false; const breakpoints = result.breakpoints; // 判断移动端断点是否匹配 if (breakpoints[Breakpoints.Handset] || breakpoints[Breakpoints.HandsetLandscape] || breakpoints[Breakpoints.HandsetPortrait]) { this.handsetView = true; console.log("screens matches handset"); } // 判断自定义宽屏断点是否匹配 else if (breakpoints[WIDESCREEN_BREAKPOINT]) { console.log('widescreen'); this.widescreenView = true; } });
关键说明
- 只有被加入
observe数组的断点,Angular CDK才会监听其状态变化,状态改变时才会触发subscribe回调。 - 原代码中
this.breakpointObserver.isMatched('(min-width: 1600px)')仅能获取当前瞬间的匹配状态,无法监听状态变化,所以窗口调整时不会触发。
内容的提问来源于stack exchange,提问作者Jonathan Ciabotaru
相关产品推荐
相关产品推荐

