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.
- Import LayoutModule in module
- Import BreakpointObserver in component
- Add dynamic value to HTML
1. Import LayoutModule in module
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 ]
})
2. Import BreakpointObserver in component
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';
});
3. Add dynamic value to HTML
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">
StackBlitz
See this StackBlitz for an example. background-color and height change when condition matches. You can see the GIF below for the effect.
