Emi*_*nge 3 angular-material angular
在桌面上,我想要rowHeight等于80vh. 但我想100vh在屏幕宽度低于 500px 时动态更改它。
我不知道该怎么做,这是代码。
超文本标记语言
<mat-grid-list cols="4" rowHeight="80vh">
<mat-grid-tile >
...
</mat-grid-tile>
</mat-grid-list>
Run Code Online (Sandbox Code Playgroud)
我不想用 CSS 来解决问题。
BreakpointObserver当您使用 Angular 的组件开发工具包 (CDK) 提供的Angular 时,您可以在没有 CSS 的情况下在 Angular 中执行此操作。
您需要执行以下步骤。
在您的 中app.module.ts,导入LayoutModule并将其添加到imports(它是 Angular 的 CDK 的一部分)。
import { LayoutModule } from '@angular/cdk/layout';
@NgModule({
imports: [BrowserModule, FormsModule, MatGridListModule, LayoutModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
Run Code Online (Sandbox Code Playgroud)
接下来,在您的组件中mat-grid-list,导入 CDK 的BreakpointObserver。它是一个可观察的对象,将检查它是否符合条件。
import { BreakpointObserver } from '@angular/cdk/layout';
Run Code Online (Sandbox Code Playgroud)
然后在组件的 中ngOnInit(),将rowHeightof设置mat-grid-list为默认值80vh,并让观察者完成其工作。
export class AppComponent implements OnInit {
rowHeight: string;
constructor(private breakpointObserver: BreakpointObserver) { }
ngOnInit() {
this.rowHeight = '80vh';
this.detectBreakpoint();
}
private detectBreakpoint(): void {
this.breakpointObserver.observe(['(max-width: 500px)']).subscribe(result => {
this.rowHeight = result.matches ? '100vh' : '80vh';
});
}
}
Run Code Online (Sandbox Code Playgroud)
如果视口宽度与给定的条件匹配(在本例中为'(max-width: 500px)'),则设置rowHeight为100vh,否则保留为80vh。
this.breakpointObserver.observe(['(max-width: 500px)']).subscribe(result => {
this.rowHeight = result.matches ? '100vh' : '80vh';
});
Run Code Online (Sandbox Code Playgroud)
最后一个更改是在 HTML 中,您需要将rowHeight组件rowHeight中的 链接到mat-grid-list.
<mat-grid-list cols="2" [rowHeight]="rowHeight">
Run Code Online (Sandbox Code Playgroud)
请参阅此 StackBlitz 的示例。background-color并height在条件匹配时更改。效果可以看下面的GIF。
Observable当组件被销毁时,不要忘记“取消订阅” ,以防止内存泄漏。

| 归档时间: |
|
| 查看次数: |
1987 次 |
| 最近记录: |