简体   繁体   中英

Angular directive cannot be used?

1) Created a new directive with 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

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

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

3) Try to use the directive as an attribute

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

4) Resulting error

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:

<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.

The docs use the binding brackets [highlightColor]="'orange'" because it's expecting a string value from the consumer to specify a color. @Input would only be needed if you are needing a value passed to the attribute directive to use in some way.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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