javascript - Angular - 组件的动态大小未更新
问题描述
我正在使用内部私有可重用组件。我的问题是当视口更新时宽度没有动态更新。以下是相关代码片段:
组件.ts
export class Component {
modalWidth: string | undefined;
ngOnInit() {
this.breakpointServiceSubscription$ = this.breakpointService.breakpoint$.subscribe(() => {
if (this.breakpointService.isSmall()) {
console.log("small")
this.modalWidth = "50px";
}
else {
this.modalWidth = "500px";
}
}
}
组件.html
<modal [width]="modalWidth">...</modal>
当浏览器调整大小时,宽度和高度应该动态变化,但它保持与渲染时相同的大小。如果我在特定视口中打开模态,则大小总是正确的,只有在我尝试在打开模态的情况下调整大小时才会出现问题。
将订阅记录到断点服务时,它始终是正确的,并且会动态记录。
我尝试将 modalWidth 和 modalHeight 转换为 observables 并在 html 中使用异步管道,但它仍然具有相同的行为。
有什么提示或建议吗?
解决方案
您可以注入ChangeDetectorRef
组件并在更改 modalWidth 后调用changeDetectorRef.detectChanges()
以让 Angular 立即将更改应用到视图。
constructor(private cdr: ChangeDetectorRef) {}
ngOnInit() {
this.breakpointServiceSubscription$ = this.breakpointService.breakpoint$.subscribe(() => {
if (this.breakpointService.isSmall()) {
console.log("small")
this.modalWidth = "50px";
}
else {
this.modalWidth = "500px";
}
// apply change immediately
this.cdr.detectChanges();
}
推荐阅读
- c++ - 编译器生成具有 constexpr 混淆行为的默认构造函数
- jquery - Laravel 数据表实现
- python - Web 使用 BeautifulSoup 在 Python 3 中的页面上抓取两个表中的第二个
- python - VS 代码无法识别 python 模块
- ffmpeg - Xvfb + ffmpeg 录制仅产生红色矩形
- database - 如果我将它用作云数据库,谷歌可以驱动多少点击?
- html - 无法格式化我的表格宽度以在移动设备上进行调整
- nunjucks - 无法在denjucks模板文件中链接css文件
- reactjs - 当他单击 Reactjs 中的警报框时,如何将用户重定向到另一个页面
- assembly - clang/ARM 程序集 - 被误解的绝对分支