Home > Net >  Angular - custom directive for preventing default behavior not working
Angular - custom directive for preventing default behavior not working

Time:07-15

I'm trying to write a directive for preventing the default behavior. Here's the code

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[app-event-blocker]',
})
export class EventBlockerDirective {
  @HostListener('drop', ['$event'])
  @HostListener('dragover', ['$event'])
  public handleEvent(event: Event) {
    event.preventDefault();
  }
}

Then i import it in shared module, declare it, and export

import { NgModule } from '@angular/core';
import { EventBlockerDirective } from './directives/event-blocker.directive';
@NgModule({
  declarations: [
    ModalComponent,
    EventBlockerDirective,
  ],
  imports: [CommonModule],
  exports: [
    EventBlockerDirective,
  ],
})
export class SharedModule {}

And then import it in Video module, where i use it

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';

@NgModule({
  declarations: [],
  imports: [CommonModule, SharedModule],
})
export class VideoModule {}

Then i use it in Video component

<div app-event-blocker>
  <h5>Drop your file here (mp4 only!)</h5>
</div>

But when i drop file in the box, it opens it in browser instead of not doing anything. When i add event handlers and prevent default behavior there it works, but i want to do it with directive. I'd appreciate if you could help me understand what is wrong with it. Full code can be found in the github repo

CodePudding user response:

Directive that provides attribute app-event-blocker is out of the current Angular module's scope

UploadComponent doesn't belong to VideoModule and declared in AppModule.
So you should import SharedModule in AppModule.

  • Related