On desktop, I want rowHeight equals to 80vh. But I would like to change it dynamically to 100vh when screen width is below 500px.
I don't know how to do it, here is the code.
HTML
<mat-grid-list cols="4" rowHeight="80vh">
<mat-grid-tile >
...
</mat-grid-tile>
</mat-grid-list>
I don't want to do a workaround with CSS.
You can do this in Angular without CSS when you use the BreakpointObserver, provided via Angular's Component Developer Kit (CDK).
What you need to do are the following steps.
In your app.module.ts, import LayoutModule and add it to imports (it's part of Angular's CDK).
import { LayoutModule } from '@angular/cdk/layout';
@NgModule({
imports: [BrowserModule, FormsModule, MatGridListModule, LayoutModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
Next to that, in your component with mat-grid-list, import CDK's BreakpointObserver. It's an observable that will check if it matches the condition.
import { BreakpointObserver } from '@angular/cdk/layout';
Then in your component's ngOnInit(), set the rowHeight of mat-grid-list to a default of 80vh and let the observer do its job.
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';
});
}
}
If the viewport width matches the condition given (in this case '(max-width: 500px)'), set rowHeight to 100vh, else keep it at 80vh.
this.breakpointObserver.observe(['(max-width: 500px)']).subscribe(result => {
this.rowHeight = result.matches ? '100vh' : '80vh';
});
The last change is in your HTML, where you need to link the rowHeight from the component to your rowHeight attribute in mat-grid-list.
<mat-grid-list cols="2" [rowHeight]="rowHeight">
See this StackBlitz for an example. background-color and height change when condition matches. You can see the GIF below for the effect.
Don't forget to 'unsubscribe' to the Observable when the component gets destroyed to prevent memory leaks.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With