我正在关注模板语法部分,以便从这里应用内置属性和结构指令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>
On browser's console I am getting the following error:
错误:模板解析错误:'t bind to ' ngclass ' since it isn' t '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进行编译 .
非常感谢您的帮助 .
1 回答
问题是由webpack loader特别是“html-loader”引起的 . html-loader以小写形式加载你在Angular中编写的所有HTML .
基本上,我的角度代码将在组件的html文件中具有ngClass指令但是当webpack编译代码并通过“html-loader”加载html时,“ngClass”将变为“ngclass”并且我将收到错误“错误:模板解析错误:无法绑定到'ngclass',因为它不是'div'的已知属性 . “
我找到了解决stackoverflow上发布的另一个问题的方法 . 以下是链接:
webpack html-loaders lowercase angular 2 built-in directives
解决方案很简单,html-loader可以设置选项 . 您需要在内部选项对象中添加以下设置:caseSensitive:true
下面是我的webpack配置文件中的html-loader设置,现在我可以成功绑定到ngClass指令 . 希望它能帮助别人 .