Angular/Material报错:无法读取未定义的属性'run'(mat-sidenav-container相关)
Hey there, let’s work through this error you’re seeing with <mat-sidenav-container>—it’s a common issue when setting up Angular Material, so we’ve got a few targeted fixes to try:
1. Ensure BrowserAnimationsModule is installed and imported
Most Angular Material components rely on animations to function properly, and missing this module is the #1 cause of this specific error.
- First, install the animations package if you haven’t already:
npm install @angular/animations - Then add
BrowserAnimationsModuleto your rootAppModule(replaceNoopAnimationsModuleif you were using that as a placeholder):import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ // ... your other imported modules (like BrowserModule, HttpClientModule) BrowserAnimationsModule ] }) export class AppModule { }
2. Verify you’ve imported all required Angular Material modules
It’s easy to miss the specific module for sidenav components. Double-check that you’ve added these to your module:
import { MatSidenavModule } from '@angular/material/sidenav'; import { MatToolbarModule } from '@angular/material/toolbar'; // Include this if you're using a toolbar with your sidenav @NgModule({ imports: [ // ... other modules MatSidenavModule, MatToolbarModule ] }) export class AppModule { }
3. Check for Angular and Material version mismatches
Version conflicts between @angular/core and @angular/material can break core functionality like the zone.js run method.
- Open your
package.jsonand confirm that the major versions of@angular/core,@angular/material, and@angular/cdkare identical (e.g., all 16.x, all 17.x). - If they’re out of sync, update Material to match your Angular version:
For example, if you’re on Angular 17:npm install @angular/material@<your-angular-major-version> @angular/cdk@<your-angular-major-version>npm install @angular/material@17 @angular/cdk@17
4. Fix Zone.js issues
The run property error points to Zone.js, which Angular uses for change detection.
- Confirm that
zone.jsis listed in yourangular.jsonunderprojects -> <your-project> -> architect -> build -> options -> scripts:"scripts": [ "node_modules/zone.js/bundles/zone.umd.js" ] - If Zone.js is missing or outdated, update it to a version compatible with your Angular release:
npm install zone.js@~<your-angular-major-version>.x
5. Clear StackBlitz environment cache
Sometimes StackBlitz’s cached dependencies can cause weird issues even after you’ve fixed your code.
- Click the refresh icon in the top-right corner of the StackBlitz editor to restart the environment.
- If that doesn’t work, try opening your project in a private browsing window to bypass browser cache.
If none of these steps resolve the error, double-check that your <mat-sidenav-container> template is structured correctly (e.g., it should contain a <mat-sidenav> and a <mat-sidenav-content> as direct children).
内容的提问来源于stack exchange,提问作者physicsboy

