【发布时间】:2018-05-02 09:32:55
【问题描述】:
我正在关注模板语法部分,以从这里https://v4.angular.io/guide/template-syntax#ngclass应用内置属性和结构指令
currentClasses: {};
setCurrentClasses() {
// CSS classes: added/removed per current state of component properties
this.currentClasses = {
'saveable': this.canSave,
'modified': !this.isUnchanged,
'special': this.isSpecial
};
}
我根据上面的 Angular 文档将 currentClasses 添加到我的 html 中:
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special</div>
在浏览器的控制台上出现以下错误:
错误:模板解析错误: 无法绑定到“ngclass”,因为它不是“div”的已知属性。
我也尝试了 ngStyle 和 ngIf,但得到了相同的错误代码。
我的 app.module.ts 包含 Common Module,因为这是一些答案中建议的解决方案 - 但这对我没有帮助:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AppComponent } from './app.component';
import { MaterialModule } from './material-module';
import { HighlightDirective } from './highlight.directive';
import { BrowserAnimationsModule } from '@angular/platform
browser/animations';
import { PlatformModule } from '@angular/cdk/platform';
import { BreakpointObserver, MediaMatcher } from '@angular/cdk/layout';
// import { MediaService } from './Media.service';
@NgModule({
declarations: [
AppComponent,
HighlightDirective
],
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
MaterialModule,
PlatformModule
],
providers: [BreakpointObserver, MediaMatcher],
bootstrap: [AppComponent]
})
export class AppModule { }
我无法独自完成这项工作,而且在遵循了对类似问题的其他一些答案之后。
我正在使用 Angular 4.4.6 和 webpack 进行编译。
非常感谢您的帮助。
【问题讨论】:
-
感谢您的评论。我仔细阅读了它,但我找不到绕过它的方法。如何使 ngclass 成为 html 元素的可绑定属性?
-
绑定到
ngClass不绑定到ngclass。错误说你绑定到ngclass,但实际上是ngClass,大写为C -
这正是我添加到组件 html 中的方式:这个 div 最初是可保存的、未更改的和特殊的。控制台日志错误消息说不能绑定到 'ngclass' 使 ngClass 为小写。我相信那是因为 webpack 是如何编译 bundle 的。 @Dummy
-
然后,其他一些组件的模板中有
ngclass,webpack 只捆绑你的代码,它是抛出错误的角度。查看整个堆栈跟踪
标签: angular angular2-directives angular-ng-class