Angular2无法绑定到DIRECTIVE,因为它不是element的已知属性 [英] Angular2 Can't bind to DIRECTIVE since it isn't a known property of element
问题描述
我通过Angular CLI生成了新的@Directive,将其导入到我的app.module.ts
I generated new @Directive by Angular CLI, it was imported it to my 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)中使用
and I try to use in my component (ChatWindowComponent)
<p [appContenteditableModel] >
Write message
</p>
即使inside指令中只有Angular CLI生成的代码:
even if within directive is only Angular CLI generated code:
import { Directive } from '@angular/core';
@Directive({
selector: '[appContenteditableModel]'
})
export class ContenteditableModelDirective {
constructor() { }
}
我得到了错误:
zone.js:388未处理的承诺拒绝:模板解析错误: 无法绑定到"appContenteditableModel",因为它不是"p"的已知属性.
zone.js:388 Unhandled Promise rejection: Template parse errors: Can't bind to 'appContenteditableModel' since it isn't a known property of 'p'.
我尝试了几乎所有可能的更改,都遵循了角度文档一切都应该起作用,但是没有.
I tried almost every possible changes, following this angular docs everything should work but it does not.
有帮助吗?
推荐答案
在将属性包装在方括号[]
中时,您试图绑定到该属性.因此,您必须将其声明为@Input
.
When wrapping a property in brackets []
you're trying to bind to it. So you have to declare it as an @Input
.
import { Directive, Input } from '@angular/core';
@Directive({
selector: '[appContenteditableModel]'
})
export class ContenteditableModelDirective {
@Input()
appContenteditableModel: string;
constructor() { }
}
重要的是,成员(appContenteditableModel
)需要被命名为DOM节点上的属性(在本例中为指令选择器).
The important part is, that the member (appContenteditableModel
) needs to be named as the property on the DOM node (and, in this case, the directive selector).
这篇关于Angular2无法绑定到DIRECTIVE,因为它不是element的已知属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!