Dustexe
Dustexe

Reputation: 123

How does *ngIf affect performance when bound to object attribute in angular?

I have a template that is used many times inside of my schedule component and displays event data. In this template I want to show some icons which represent whether the event is private, read-only, etc.

In current implementation I achieved this with "*ngIf" that is bound to objects attribute.

<ng-template #mEventTemplate let-activity="activity">
  <div class="template-wrap d-flex flex-column">
    <div class="d-flex justify-content-between" style="font-size: 10px">
      <span>{{activity[this.fields.startTime.name] | getTimeString}} - {{activity[this.fields.endTime.name] | getTimeString}}</span>
      <div>
        <i class="fa fa-lock ml-1" *ngIf="activity['isPrivate']"></i></i>
      </div>
    </div>
    <span>{{activity[this.fields.subject.name]}}</span>
  </div>
</ng-template>

My problem is that when using more of those icons with *ngIf-s the performance drastically decreases when I am dragging events around the schedule. Even more so if I'm holding any of my keyboard keys (ctrl for example to copy event when drop is triggered). If I remove the whole <ng-template></ng-template> or just *ngIf elements the dragging becomes smooth.

Is there something that I can do here? or is this the way to go?

Upvotes: 3

Views: 1935

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

Are you using OnPush change detection? This will ensure you have control over when change detection is run.

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
  constructor(private changeDetector: ChangeDetectorRef) {
  }

  method(): void {
    // do stuff here

    // now tell Angular you want it to chack for changes
    this.changeDetector.detectChanges();
  }
}

I doubt that checking ngIf against an object has any difference from checking against a simple value - ultimately it's just a javascript "truthy" evaluation.

Upvotes: 1

Related Questions