Angular2 不能绑定到 DIRECTIVE,因为它不是元素的已知属性

新手上路,请多包涵

我通过 Angular CLI 生成了新的 @Directive,它被导入到我的 app.module.ts

 import { ContenteditableModelDirective } from './directives/contenteditable-model.directive';

import { ChatWindowComponent } from './chat-window/chat-window.component';

@NgModule({
  declarations: [
    AppComponent,
    ContenteditableModelDirective,
    ChatWindowComponent,
    ...
  ],
  imports: [
    ...
  ],
  ...
})

我尝试在我的组件中使用(ChatWindowComponent)

 <p [appContenteditableModel] >
    Write message
</p>

即使 inside 指令只是 Angular CLI 生成的代码:

  import { Directive } from '@angular/core';

 @Directive({
   selector: '[appContenteditableModel]'
 })
 export class ContenteditableModelDirective {

 constructor() { }

 }

我得到了错误:

zone.js:388 未处理的承诺拒绝:模板解析错误:无法绑定到“appContenteditableModel”,因为它不是“p”的已知属性。

我尝试了几乎所有可能的更改,按照这个 角度文档,一切都应该工作,但它没有。

有什么帮助吗?

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

阅读 768
2 个回答

将属性包装在括号中时 [] 您正在尝试绑定到它。因此,您必须将其声明为 @Input

 import { Directive, Input } from '@angular/core';

@Directive({
 selector: '[appContenteditableModel]'
})
export class ContenteditableModelDirective {

  @Input()
  appContenteditableModel: string;

  constructor() { }

}

重要的部分是,成员( appContenteditableModel )需要被命名为 DOM 节点上的属性(在本例中为指令选择器)。

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

我在共享模块中声明的指令面临同样的问题。我正在使用这个指令来禁用表单控件。

 import { Directive, Input } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[appDisableControl]'
})
export class DisableControlDirective {

  constructor(private ngControl: NgControl) { }

  @Input('disableControl') set disableControl( condition: boolean) {
    const action = condition ? 'disable' : 'enable';
    this.ngControl.control[action]();
  }

}

要使其正常工作,请在共享模块(或您正在使用的任何模块)中声明和导出指令。

 import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DisableControlDirective } from './directives/disable-control/disable-control.directive';

@NgModule({
  declarations: [
    DisableControlDirective
  ],
  imports: [
    CommonModule
  ],
  exports: [DisableControlDirective],
  providers: [],
  bootstrap: []
})
export class SharedModule { }

现在我们可以在导入 SharedModule 的任何模块中使用该指令。

现在要禁用响应式表单的控件,我们可以像这样使用它:

 <input type="text" class="form-control" name="userName" formControlName="userName" appDisableControl [disableControl]="disable" />

错误我正在这样做,我只使用选择器(appDisableControl)并将禁用参数传递给它。但是要传递输入参数,我们必须像上面一样使用它。

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

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