Angular4 异常:无法绑定到“ngClass”,因为它不是“输入”的已知属性

新手上路,请多包涵

在我的项目中,我使用延迟加载因此,在我的注册模块中,当 formGroup 在我的注册表单上有一些验证错误时,我使用 [ngClass] 指令添加无效类。但是当我尝试在我的表单上添加 [ngClass] 指令时,我的代码会引发异常。

无法绑定到“ngClass”,因为它不是“输入”的已知属性

在调查错误本身时,我找到了几种解决方案,例如将“指令:[NgStyle]”添加到组件中,但这并不能解决问题。

这是我的代码:

注册路由器.ts

 import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RegisterComponent } from "app/modules/register/register.component";

const routes: Routes = [
{
    path: '', pathMatch: 'full',
    component: RegisterComponent
}
];

@NgModule({
    imports: [
    RouterModule.forChild(routes),
    FormsModule,
    ReactiveFormsModule
],
declarations: [RegisterComponent],
    exports: [RouterModule]
})
export class RegisterRouter { }

注册模块.ts

 import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RegisterRouter } from './register.router';

@NgModule({
    imports: [
      CommonModule,
      RegisterRouter
],
    declarations: []
})
export class RegisterModule { }

注册组件.ts

 import { Component, OnInit, ViewContainerRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

    @Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {

//#region Declarations
    UserForm: FormGroup;
    inValid: boolean = false;
//#endregion

constructor(
    private _fb: FormBuilder) {
    this.UserForm =  _fb.group({
    "_firstname" : ['', Validators.required]
    });
}
}

register.component.html

 <input type="text" class="form-control" [ngClass]="{'ahinValid': inValid}" id="txtFirst_Name" aria-describedby="ariaFirstName" placeholder="Enter First Name"
          name="_firstname" [formControl]="UserForm.controls['_firstname']">

谢谢您的帮助。

原文由 Ahmer Ali Ahsan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 806
2 个回答

由于 RegisterComponentRegisterRouter (模块的名称是什么?)模块中声明,那么你必须导入 CommonModule 那里:

 @NgModule({
  imports: [
    RouterModule.forChild(routes),
    FormsModule,
    ReactiveFormsModule,
    CommonModule      <================== this line
  ],
  declarations: [
    RegisterComponent // this component wants to have access to built-in directives
  ],
  exports: [RouterModule]
})
export class RegisterRouter { }

原文由 yurzui 发布,翻译遵循 CC BY-SA 3.0 许可协议

就我而言,它不需要 CommonModule 导入。我刚刚输入了 [ngclass] 而不是 [ngClass]。我猜它区分大小写,它需要大写“C”,而不是“c”。

原文由 Sotiris Zegiannis 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进