Brendan Crowley
Brendan Crowley

Reputation: 79

Avoid html repetition

I have the following html, params.formGroup.controls[params.fieldName].value is repeated in ngbTooltip and looks ugly, is there some way to re-write that line to avoid the repetition of params.formGroup.controls[params.fieldName].value?

<div class="svg-class">
    <svg [id]="params.id"
    [ngbTooltip]="allTrans[params.formGroup.controls[params.fieldName].value] ?
        allTrans[params.formGroup.controls[params.fieldName].value] :
        params.formGroup.controls[params.fieldName].value"
    container="body"
    triggers="manual">
    </svg>
</div>

Upvotes: 2

Views: 94

Answers (1)

Barremian
Barremian

Reputation: 31105

You could try to use the *ngIf directive's as construct with the <ng-container> element.

  1. <ng-container> is commented out in the final DOM and so does not lead to bloat.
  2. Note that now you're implicitly checking if params.formGroup.controls[params.fieldName].value is defined.
<div class="svg-class">
  <ng-container *ngIf="params.formGroup.controls[params.fieldName].value as fieldName">
    <svg [id]="params.id"
      [ngbTooltip]="allTrans[fieldName] ? allTrans[fieldName] : fieldName"
      container="body"
      triggers="manual"
    >
    </svg>
</div>

From Angular v12.0.0 (#36528) you'd also be able to use nullish coalescing operator (??) instead of the ternary operator

<svg [id]="params.id"
  [ngbTooltip]="allTrans[fieldName] ?? fieldName"
  container="body"
  triggers="manual"
>
</svg>

Upvotes: 1

Related Questions