1) 使用 angularCLI 创建了一个新指令。
import {Directive, ElementRef, OnInit} from '@angular/core';
@Directive({
selector: '[scrollable]'
})
export class ScrollableDirective implements OnInit{
constructor(public el:ElementRef) { }
ngOnInit(){
console.log('its working!')
}
}
2) Angular CLI 自动将指令添加到 app.module 声明中
import { ScrollableDirective } from './scrollable/scrollable.directive';
@NgModule({
declarations: [
...
ScrollableDirective
],
3)尝试使用指令作为属性
<div class="menu-container" *ngIf="menuService.showMenu" [scrollable]>
4) 结果错误
Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'scrollable' since it isn't a known property of 'div'.
我已阅读官方文档,我似乎正在做所有正确的事情。我不明白我可能错过了什么以及为什么不能使用该指令。
最佳答案
尝试添加不带 []
绑定(bind)的 scrollable
指令:
<div class="menu-container" *ngIf="menuService.showMenu" scrollable>
如果您向指令传递一个值,但您没有在指令中使用任何 @Input
值,则 []
会是这样,所以它不会需要。
docs使用绑定(bind)括号 [highlightColor]="'orange'"
因为它期望来自消费者的字符串值来指定颜色。仅当您需要将值传递给属性指令以便以某种方式使用时,才需要 @Input
。
@Kevin 是对的,错误是由于 @Input 未添加到指令配置中引起的,但在这种情况下您不需要它,因此请避免导入/导出该装饰器。
关于javascript - 无法使用 Angular Directive(指令)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45110734/