[英]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.