user12707940
user12707940

Reputation: 161

Angular - How can I refactor *ngIf condition?

In my angular code, I have 2 conditions set

Condition 1 - If weatherService.display is false then show data as Link

Condition 2 - If weatherService.display is true then do not show data as Link

I see there is code being duplicated for the data that will be shown as link or not.

Is there any way I can optimize this code where inline-edit-input> is same?

Condition 1 below (Data shown as Link)

  <a [href]="'/nature/'+lp.position+'-'+trial" *ngIf="!weatherService.display"><span>{{runLandText[i]}}</span>
  <inline-edit-input id="runLand_{{i}}" [editable]="weatherService.display && runLandHasNoChildren[i]"
                     (saved)="runLandEdited(i)">
    <mat-form-field>
      <input inlineEditTag matInput type="text" [(ngModel)]="runLandEdit[i]">
    </mat-form-field>
  </inline-edit-input>
  </a>

Condition 2 below (Data not shown as Link)


  <span *ngIf="weatherService.display"><span>{{runLandText[i]}}</span>
  <inline-edit-input id="runLand_{{i}}" [editable]="weatherService.display && runLandHasNoChildren[i]"
                     (saved)="runLandEdited(i)">
    <mat-form-field>
      <input inlineEditTag matInput type="text" [(ngModel)]="runLandEdit[i]">
    </mat-form-field>   
    </inline-edit-input>
  </span>

Upvotes: 0

Views: 286

Answers (1)

KShewengger
KShewengger

Reputation: 8269

You can implement it with ng-template and ng-container

Have created a Stackblitz Demo for your reference

Ng-Template

<ng-template #inlineEditInput let-i="index">
  <span>{{ runLandText[i] }}</span>

  <inline-edit-input id="runLand_{{i}}" [editable]="weatherService.display && runLandHasNoChildren[i]" (saved)="runLandEdited(i)">
     <mat-form-field>
      <input inlineEditTag matInput type="text" [(ngModel)]="runLandEdit[i]">
     </mat-form-field>   
  </inline-edit-input>

</ng-template>

Condition #1

<a [href]="'/nature/'+lp.position+'-'+trial" *ngIf="!weatherService.display">
  <ng-container [ngTemplateOutlet]="inlineEditInput"
                [ngTemplateOutletContext]="{ index: i }"></ng-container>
</a>   

Condition #2

<span *ngIf="weatherService.display">
  <ng-container [ngTemplateOutlet]="inlineEditInput"
                [ngTemplateOutletContext]="{ index: i }"></ng-container>
</span>   

NOTE:

  • ngTemplateOutlet renders your ng-template inside your div or in our case we used ng-container
  • ngTemplateOutletContext is your outlet to send data to your ng-template

Upvotes: 1

Related Questions