angular - 在组件元素上使用指令

标签 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>")

我是否缺少让组件将属性识别为指令而不是组件输入的内容。

最佳答案

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

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

//应用模块:

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

关于angular - 在组件元素上使用指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40259513/

相关文章:

对于 ng-select 控件的自定义验证,Angular 2 表单状态始终无效

angular - 如何在不循环所有内容的情况下获取 Angular2 模板中数组的最后一个元素?

Angular4图像上传到s3存储桶并将响应存储到全局变量中,可以访问其他方法/函数

angular - 如何从指令中观察服务内简单变量的变化?

class - Angular 2 : Functions to be used across all components

angular2 - DatepickerConfig 没有服务提供商

javascript - 如何通过异步 httpclient 调用使用 ngx-bootstrap typeahead

javascript - Angular 选择类 if else

放置在延迟加载模块的组件中时,Angular 6 指令未初始化

javascript - Angular 2 中的绑定(bind)数据