简体   繁体   English

无法使用Angular指令?

[英]Angular directive cannot be used?

1) Created a new directive with angularCLI. 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 automatically adds the directive to the app.module declarations 2)Angular CLI自动将指令添加到app.module声明中

import { ScrollableDirective } from './scrollable/scrollable.directive';

@NgModule({
  declarations: [
    ...
    ScrollableDirective
  ],

3) Try to use the directive as an attribute 3)尝试将指令用作属性

<div class="menu-container" *ngIf="menuService.showMenu" [scrollable]>

4) Resulting error 4)产生的错误

Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'scrollable' since it isn't a known property of 'div'.

I have read the official documentation and I seem to be doing all the right things. 我已经阅读了官方文档,并且似乎在做所有正确的事情。 I cannot understand what I could have missed and why the directive cannot be used. 我不明白自己可能错过了什么以及为什么不能使用该指令。

Try adding the scrollable directive without the [] bindings: 尝试添加不带[]绑定的scrollable指令:

<div class="menu-container" *ngIf="menuService.showMenu" scrollable>

[] would be if you are passing a value to the directive, but you aren't utilizing any @Input values in you directive, so it would not be needed. 如果要向指令传递值,则使用[]即可,但是您没有在指令中使用任何@Input值,因此不需要它。

The docs use the binding brackets [highlightColor]="'orange'" because it's expecting a string value from the consumer to specify a color. 文档使用绑定括号[highlightColor]="'orange'"因为它期望使用者使用字符串值来指定颜色。 @Input would only be needed if you are needing a value passed to the attribute directive to use in some way. 仅当需要将值传递给attribute指令以某种方式使用时,才需要@Input

@Kevin is right that the error is being caused by @Input not being added to the directive configuration, but in this case you don't need it, so avoid the import/export of that decorator. @Kevin是正确的,该错误是由于@Input没有添加到指令配置中引起的,但是在这种情况下,您不需要它,因此请避免该装饰器的导入/导出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM