Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function inside ngIf is called multiple times, after a single click event- Angular2_Typescript

Hello this is the first time I qm putting question on stackoverflow. I am developing an application in angular2: v2.1.0 (typescript- v2.0.10). I am using "ng2-file-upload" for file upload. The HTML code is as follows:

<div class="container-fluid">
    <h5 class="titleCenter"> File Upload </h5>
    <div class="drop-zone" ng2FileDrop
         [ngClass]="{'nv-file-over': hasBaseDropZoneOver, 'pointerBan': testDisablDropZone}"
         (fileOver)="fileOverBase($event)"
         [uploader]="uploader">
        <span *ngIf="isUploaderEmpty(uploader.queue)">Drop Down box for the CSV file only...!!!</span>
        <span *ngFor="let item of uploader.queue" >
            <p class="row" >
                <i class="fileIcon"></i>
                <strong>{{ item?.file?.name }}</strong>
                <a class="fileUploadRemoveButton fa fa-times-circle" (click)="item.remove()"></a>
            </p>
        </span>
    </div>
    <div  [ngClass]="{'activeCheckButton': testDisablDropZone}" class="CheckboxZone" (click)="disableDropZone($event)" style="margin-top: 10px">
        <span>Click here to disable the dropdown box.</span>
    </div>
</div>
<button type="button" (click)="test($event)">click</button>

Here when I clicked on the div with the class 'CheckboxZone' it calls the function 'disableDropZone($event)' but after that it calls the function 'idUploadEmpty()' too. The same case with the button Click too. The code of the component is as follows:

const URL = 'https://evening-anchorage-3159.herokuapp.com/api/';
@Component({
    selector: 'fileupload',
    templateUrl: './fileupload.component.html',
    styleUrls: ['./fileupload.component.scss']
})
export default class FileuploadComponent {
public uploader:FileUploader = new FileUploader({url: URL, autoUpload:true, allowedMimeType:['text/csv'] });
public hasBaseDropZoneOver:boolean = false;
public hasAnotherDropZoneOver:boolean = false;
private fileType =['json'];
private flagFile = false;
private testDisablDropZone = false;
private fileNotAccepted = false;
public fileOverBase(e:any):void {
    this.hasBaseDropZoneOver = e;
    console.log('EVENT fileOverBase : ', e);
}

public fileOverAnother(e:any):void {
    this.hasAnotherDropZoneOver = e;
    console.log('fileOverAnother : ', e);
}

isUploaderEmpty (uploaderQueue): boolean {
    console.log('Queue pqssed from View : ',this.uploader.queue);
    let qLength = uploaderQueue.length;
    if(uploaderQueue.length==0){
        this.fileNotAccepted = true;
        return true;}

    if (qLength > 1){
        uploaderQueue.pop();
        this.flagFile = true;
        let timer = Observable.timer(3000,10000);
        timer.subscribe(t=>{
            this.flagFile = false
        });
    }
    return false;
}

disableDropZone () {
    console.log('disableDropZone clicked...!!!');
    this.testDisablDropZone =! this.testDisablDropZone;
}

test(event)  {
    console.log('OK')
}
}

Hard to understand why it is calling the function 'isUploaderEmpty()' all the time when an event is triggered.

Thank you.

like image 273
NRP Avatar asked Dec 20 '16 11:12

NRP


People also ask

What is * in * ngIf?

The * syntax means that ngIf is a structural directive, meaning that it affects the structure of the page.

What is * ngIf and how does it work?

NgIflink. A structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause.

Is Hidden faster than ngIf?

Both are the same in terms of performance, becouse both are angular common atributes (*ngIf === [ngIf]) and they work equal at angular rendering. Save this answer.

Can we have two ngIf in angular?

We can use multiple conditions in *ngIf with logical operator AND (&&) to decide the trustworthy of *ngIf expression. If all conditions are true, then element will be added to the DOM.


1 Answers

It's actually quite easy.

When ever you define an ngIf , you put an expression inside it right ?

That means every time there is an update inside that component , Angular needs to make sure that the expression inside the ngIf is evaluated. ( This is what you expect from Angular right ? other wise why would you use ngIf ?)

So every time there is an update in the model , or rather , every time there is something that triggers the changeDetection, Angular evaluates that expression , which in your case is a function ( isUploaderEmpty ).

Generally , events are one of the things that fire a changeDetection( it's more complicated than this ).

So that's why :D.

like image 96
Milad Avatar answered Oct 12 '22 04:10

Milad