1

It's known that first ngOnChanges fires before bindings are initialized. So it's common to add safe navigation operator into expressions.

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: 'some-component',
    templateUrl: '<div>{{item?.name}} {{item?.surname}}</div>'
})
export class SomeComponent {

    @Input() item: { name: string; surname: string; };

}

But I guess if that approach have drawbacks on performance. Then would the code below will be faster?

<div *ngIf="item">{{item.name}} {{item.surname}}</div>

Especially for the components with many item?. checks in a template.

Dzmitry Vasilevsky
  • 1,295
  • 2
  • 14
  • 25
  • I haven't ran any tests ... but I would think that `ngIf` would be slower because it's adding/removing items from the DOM. The safe navigation operator is just deciding of a value is null or not null. – DeborahK Feb 13 '19 at 17:18
  • Also, the original proposal for the safe navigation operator discusses this a bit here: https://github.com/angular/angular/issues/791 – DeborahK Feb 13 '19 at 17:29
  • @DeborahK Good catch. But the question is how slower DOM insertion is then additional checks caused by safe operator. It's definitely slower in my example with just two safe operators but what if there are dozens of it? – Dzmitry Vasilevsky Feb 14 '19 at 08:44
  • How are you measuring that? – DeborahK Feb 14 '19 at 08:51
  • It's just an assumption. That's why I have created this post. I guess permormance.now() residual from ngDoCheck to ngAfterComponentChecked would work. I'll try this – Dzmitry Vasilevsky Feb 14 '19 at 10:19

0 Answers0