如何在Angular 5的Angular Material中实现类似Bootstrap栅格的元素定位
Hey there! I totally get your frustration here—Angular Material 2+ (the version compatible with Angular 5) made a significant shift from AngularJS Material when it comes to layout, ditching those familiar layout and layout-align attributes entirely. Don't worry though, there are solid alternatives to achieve the same grid/positioning behavior you're used to.
1. Use Angular Flex Layout (Official Recommended Approach)
Angular Flex Layout is a dedicated library built to work seamlessly with Angular Material, and it mirrors the declarative layout syntax you loved in AngularJS Material. Here's how to get started:
- First, install the library along with Angular CDK (a required dependency):
npm install @angular/flex-layout @angular/cdk - Import
FlexLayoutModuleinto your Angular module (e.g.,AppModule):import { FlexLayoutModule } from '@angular/flex-layout'; @NgModule({ imports: [ // ... other core imports like BrowserModule, MatButtonModule, etc. FlexLayoutModule ] }) export class AppModule { } - Now you can use directives that directly replace the old AngularJS Material attributes. For example, your original code:
Becomes this with Flex Layout:<div layout="row" layout-align="space-around center"> <!-- Your elements here --> </div>
It supports all the same layout configurations (rows/columns, alignment, responsive breakpoints, etc.) you're familiar with.<div fxLayout="row" fxLayoutAlign="space-around center"> <!-- Your elements here --> </div>
2. Use Angular Material's Built-in MatGridList Component
If you're looking for a Bootstrap-style grid system, Angular Material has the MatGridList component designed specifically for grid-based layouts. It lets you define columns and row heights, and automatically adjusts for responsiveness:
- First, import
MatGridListModuleinto your module:import { MatGridListModule } from '@angular/material/grid-list'; @NgModule({ imports: [ // ... other imports MatGridListModule ] }) export class AppModule { } - Example usage:
<!-- 3-column grid, with row height ratio 2:1 and 16px gutters --> <mat-grid-list cols="3" rowHeight="2:1" gutterSize="16px"> <mat-grid-tile>First Tile</mat-grid-tile> <mat-grid-tile>Second Tile</mat-grid-tile> <mat-grid-tile>Third Tile</mat-grid-tile> <mat-grid-tile colspan="2">Wide Tile (spans 2 columns)</mat-grid-tile> </mat-grid-list>
3. Direct CSS Flexbox (No Extra Libraries)
Since Angular Material is built on top of CSS Flexbox, you can also write plain CSS to achieve custom layouts. This is great for one-off positioning needs:
- For your original example, the equivalent CSS would be:
<div class="custom-row-layout"> <!-- Your elements here --> </div>.custom-row-layout { display: flex; flex-direction: row; justify-content: space-around; /* Matches layout-align's space-around */ align-items: center; /* Matches layout-align's center */ }
内容的提问来源于stack exchange,提问作者Ahmed Elkoussy

