Angular 6添加组件与安装Angular Material时遇错误求助
Hey there! Let's work through these two Angular 6 issues step by step—they're totally common when you're starting out, so no need to stress 😊
1. Fixing the ng add component heroes Error
First off, let's clear up a command mix-up: ng add is meant for adding dependency packages (like Angular Material) to your project, not for generating components. That's why you're seeing that schema validation error about the dryRun property—it doesn't belong in the ng add workflow.
The correct command to generate a new component in Angular 6 is:
ng generate component heroes # Or the shorter, more common version: ng g c heroes
This command will properly create all the component files (.ts, .html, .css, .spec.ts) and automatically update your module's declarations to include the new component.
2. Fixing the Template Parse Errors After Installing Angular Material
The unexpected token ? error stems from two key issues with your setup:
- Version Mismatch: Angular Material versions must align exactly with your Angular core version. If you installed the latest Material package, it’s likely using syntax that Angular 6 doesn’t support.
- Strict Expression Parsing: Angular 6’s template parser is stricter about operator precedence—you need to wrap the
asyncpipe result in parentheses to avoid parsing confusion.
Here’s how to fix it:
Step 1: Install Angular Material 6.x (Compatible with Angular 6)
First, uninstall the mismatched Material packages:
npm uninstall @angular/material @angular/cdk
Then install the 6.x versions that are built for Angular 6:
npm install @angular/material@6.x @angular/cdk@6.x
Step 2: Correct the Template Expressions
In your MyMenuComponent.html, update all expressions using the async pipe with ternary operators by wrapping the pipe result in parentheses. This tells the parser to resolve the async stream first before evaluating the conditional logic.
Before:
[attr.role]="isHandset$ | async ? 'dialog' : 'navigation'" [mode]="isHandset$ | async ? 'over' : 'side'" [opened]="!(isHandset$ | async)"
After:
[attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'" [mode]="(isHandset$ | async) ? 'over' : 'side'" [opened]="!((isHandset$ | async))"
内容的提问来源于stack exchange,提问作者Hendri Triwanto

