bigmeister
bigmeister

Reputation: 1227

Angular 4; ngIf statement; multiple conditions

I need your help

There is my code below:

      <mat-cell *matCellDef="let row">
        <span *ngIf="row.messageText.length >= 30">{{row.messageText.substr(0, 25)}}</span>
        <span *ngIf="row.messageText.length < 30">{{row.messageText.substr(0, 30)}}</span>
        <span *ngIf="(row.messageText == null) || (row.messageText === 'undefined'">.....</span>
      </mat-cell>

I don't know if I use ngIf directives properly.

I need to show span with "row.messageText.substr(0, 25) if messageText's length is longer or equal to 30.

If row.messageText length is shorter than 30, I need to show span with row.messageText.substr(0, 30).

And if row.messageText is null or undefined, I'd like to have "....." in the span.

Please help me use ngIf correctly.

Upvotes: 1

Views: 7768

Answers (2)

In situation like you mention, it is better to use switch case statement as below:

<div [ngSwitch]="true">
    <div *ngSwitchCase="row.messageText.length >= 30">
        <span>{{row.messageText.substr(0, 25)}}</span>
    </div>
    <div *ngSwitchCase="row.messageText.length < 30">
        <span>{{row.messageText.substr(0, 30)}}</span>
    </div>
    <div *ngSwitchCase="(row.messageText == null) || (row.messageText === 'undefined'">
        <span>...</span>
    </div>
    <div *ngSwitchDefault>
        <span></span>
    </div>
</div>  

Upvotes: 2

Danilo Dughetti
Danilo Dughetti

Reputation: 1370

I'd define the conditions in the ngOnInit:

private condition: boolean = false;

ngOnInit(){
   this.condition = (row.messageText.length >= 30);
}

then:

 <mat-cell *matCellDef="let row">
        <span *ngIf="row.messageText && condition">{{row.messageText.substr(0, 25)}}</span>
        <span *ngIf="row.messageText && !condition">{{row.messageText.substr(0, 30)}}</span>
        <span *ngIf="!row.messageText">.....</span>
      </mat-cell>

Bye

Upvotes: 1

Related Questions