2

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>
  • 1
    I'm not very fluent in Angular, but an idea would be to modify that to `[ngbTooltip]=somefunction(params.formGroup.controls, allTrans)`. If somehow you can call a function at this point. – Lajos Arpad May 11 '21 at 15:38
  • 2
    @LajosArpad: This would be a bad idea if OP is using default change detection strategy in their component. In that case the function would be triggered for each change detection cycle and might lead to performance issues. See here for more info: https://stackoverflow.com/a/45207623/6513921 – ruth May 12 '21 at 06:03

1 Answers1

1

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>
ruth
  • 29,535
  • 4
  • 30
  • 57