在组件元素上使用指令

时间:2016-10-26 10:14:30

标签: angular angular2-directives angular2-components

如果可能的话,我会尝试锻炼。

我正在尝试在组件元素上放置一个指令

WrapperComponent.ts

@Component({
    selector: 'app-wrapper',
    template: '<div><app-component draggable></app-component></div>'
})
export class WrapperComponent implements OnInit {

    constructor() {

    }

    ngOnInit() {
      //Code Here
    }
}

AppComponent.ts

@Component({
    selector: 'app-component',
    template: '<div>Sample Text</div>'
})
export class AppComponent implements OnInit {

    constructor() {

    }

    ngOnInit() {
      //Code Here
    }
}

DraggableDirective.ts

@directive({
    selector: '[draggable]',
})
export class DraggableDirective implements OnInit {

    constructor(private _element: ElementRef, renderer: Renderer) {

    }

    ngOnInit() {
      //Code Here

    }
}

但是当我这样做时,我得到了这个错误

zone.js:355 Unhandled Promise rejection: Template parse errors:
Can't bind to 'Draggable' since it isn't a known property of 'app-component'.
1. If 'app-component' is an Angular component and it has 'draggable' input, then verify that it is part of this module.
2. If 'app-component' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
 ("<div>
    <app-component [ardDraggable]="true"></app-component>
</div>")

是否有一些我缺少的东西使组件将属性识别为指令而不是组件的输入。

1 个答案:

答案 0 :(得分:1)

AppComponent中更改您的选择器,并确保您已将WrapperComponentAppComponentDraggableDirective添加到ngModule声明中:

@Component({
  selector: 'app-component',
  template: '<div>Sample Text</div>'
})

//的AppModule:

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, WrapperComponent, DraggableDirective ],
  bootstrap:    [ WrapperComponent ]
})