Error if don't check if {{object.field}} exists

后端 未结 1 1074
名媛妹妹
名媛妹妹 2020-11-22 11:54

I have a question about checking if some field in object exists.

I want to print all categories which user has so I\'m doing something like this:

  &         


        
1条回答
  •  北海茫月
    2020-11-22 12:42

    basic usage

    Use the safe-navigation operator

    {{category?.name}}
    

    then name is only read when category is not null.

    array

    This only works for the . (dereference) operator. For an array you can use

    {{records && records[0]}}
    

    See also Angular 2 - Cannot read property '0' of undefined error with context ERROR CONTEXT: [object Object]

    async pipe

    With async pipe it can be used like

    {{(chapters | async)?.length
    

    ngModel

    With ngModel currently it needs to be split into

    [ngModel]="details?.firstname" (ngModelChange)="details.firstname = $event"
    

    See also Data is not appending to template in angular2

    *ngIf

    An alternative is always to wrap the part of the view with *ngIf="data" to prevent the part being rendered at all before the data is available to prevent the dereference error.

    0 讨论(0)
提交回复
热议问题