[英]Angular directive cannot be used?
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'.
我已经阅读了官方文档,并且似乎在做所有正确的事情。 我不明白自己可能错过了什么以及为什么不能使用该指令。
尝试添加不带[]
绑定的scrollable
指令:
<div class="menu-container" *ngIf="menuService.showMenu" scrollable>
如果要向指令传递值,则使用[]
即可,但是您没有在指令中使用任何@Input
值,因此不需要它。
文档使用绑定括号[highlightColor]="'orange'"
因为它期望使用者使用字符串值来指定颜色。 仅当需要将值传递给attribute指令以某种方式使用时,才需要@Input
。
@Kevin是正确的,该错误是由于@Input没有添加到指令配置中引起的,但是在这种情况下,您不需要它,因此请避免该装饰器的导入/导出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.