1

I have a drag and drop container written in Angular 2 typescript. I want to change the background color of the drag & drop container while I am dragging a file into the container.

Typescript:

@HostListener('dragover', ['$event']) public onDragOver(evt){
 evt.preventDefault();
 evt.stopPropagation();
}

@HostListener('dragleave', ['$event']) public onDragLeave(evt){
 evt.preventDefault();
 evt.stopPropagation();
}

@HostListener('drop', ['$event']) public onDrop(evt){
 evt.preventDefault();
 evt.stopPropagation();
 let files = evt.dataTransfer.files;
 let valid_files : Array<File> = [];
 let invalid_files : Array<File> = [];
 if(files.length > 0){
   forEach(files, (file: File) =>{
     let ext = file.name.split('.')[file.name.split('.').length - 1];
     if(this.allowed_extensions.lastIndexOf(ext) != -1){
       valid_files.push(file);
     }else{
       invalid_files.push(file);
     }
   });
   this.filesChangeEmiter.emit(valid_files);
   this.filesInvalidEmiter.emit(invalid_files);
 } 
}

HTML:

<div class="dropzone" (filesChangeEmiter)="onFilesChange($event)"
    (filesInvalidEmiter)="onFileInvalids($event)">
   <div class="centered">Drop your file here!</div>
</div>

I tired to use HostBinding to change the background color, but it doesn't work. How can I detect dragging state and change its CSS?

Matt-pow
  • 946
  • 4
  • 18
  • 31

1 Answers1

1

You can simply specify [ngStyle] in your tag as below.

Define one variable in component for back color like:

let backColor:string="transparent";

Set above variable value in your drop event and use as below.

(1) Inline CSS with [ngStyle] like

(2) Return style from component like

 private setStyles(): any {
    let styles = {
        'background-color': this.backColor
    };      
    return styles;
}