Angular2 Can't bind to DIRECTIVE since it isn't a known property of element

Tomas Javurek picture Tomas Javurek · Nov 20, 2016 · Viewed 77.6k times · Source

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: [
    ...
  ],
  ...
})

and I try to use in my component (ChatWindowComponent)

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

even if within directive is only Angular CLI generated code:

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

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

 constructor() { }

 }

I got the error:

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.

Any help?

Answer

naeramarth7 picture naeramarth7 · Nov 20, 2016

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() { }

}

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).