Home > Net >  Angular & Typescript: Replace value if it matches a given string
Angular & Typescript: Replace value if it matches a given string

Time:09-13

I have an app that was written in angular and its purpose is to display metadata values of several items coming from a database. My goal is to rewrite the output of one metadatavalue, if it matches a given string (for example: If the metadatavalue matches "CC-BY-ND" it should output a link to the Creative Commons Website instead).

This is my Typescript-File ("metadata-values.component.ts"):

import { Component, Input } from '@angular/core';
import { MetadataValue } from '../../../core/shared/metadata.models';

/**
 * This component renders the configured 'values' into the ds-metadata-field-wrapper component.
 * It puts the given 'separator' between each two values.
 */
@Component({
  selector: 'ds-metadata-values',
  styleUrls: ['./metadata-values.component.scss'],
  templateUrl: './metadata-values.component.html'
})
export class MetadataValuesComponent {

  /**
   * The metadata values to display
   */
  @Input() mdValues: MetadataValue[];
  /**
   * The seperator used to split the metadata values (can contain HTML)
   */
  @Input() separator: string;

  /**
   * The label for this iteration of metadata values
   */
  @Input() label: string;

}

And this is my html file ("metadata-values.component.html"):

<ds-metadata-field-wrapper [label]="label | translate">
    <span  *ngFor="let mdValue of mdValues; let last=last;">
        {{mdValue.value}}<span *ngIf="!last" [innerHTML]="separator"></span>
    </span>
</ds-metadata-field-wrapper>

So basically I want to check if {{mdValue.value}} matches for example "CC-ND-BY" and replace the output with something else. Unfortunately my understanding of Typescript is very limited, so I would very much appreciate some help with my problem. :-( Thanks in advance to anyone reading this!

CodePudding user response:

You can directly check for the string match in your HTML template. For example

<ds-metadata-field-wrapper [label]="label | translate">
    <span  *ngFor="let mdValue of mdValues; let last=last;">
        {{ mdValue.value === 'CC-ND-BY' ? 'Value Matches String': mdValue.value }}
    <span *ngIf="!last" [innerHTML]="separator"></span>
    </span>
</ds-metadata-field-wrapper>

This is a very simple example considering you only want to match with a single string. I hope this can give you the guide to building more complex logic

Also, try to avoid calling a function directly in your HTML template. Performance wise it will run multiple times on every change detection i.e. in the answer given translateValue() will work but it's not the best approach.

The better approach would be to create a PIPE and use it or directly add your logic in the HTML template like I did in the example above.

CodePudding user response:

You can use indexOf on your string to see if it returns a value greater than -1. -1 being the default return of indexOf if there is no match. You can then combine this with a custom pipe, which might be overkill, or just do a basic method inside of your component like so:

translateValue(value: string) {

   //negative case. 
   if(value.indexOf("whateveryouarelookingfor") == -1)
      return value;

   return "your changed value";
}

then in your HTML your {{mdValue.value}} turns into {translateValue(mdValue.value)}}

Edit: Documentation for string.indexOf https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf


Edit 2:

As mentioned by Hassan, a Pipe would be a preferred approach. The way to do it would be as follows:

  • Create a pipe and make sure you decorate it as such
  • Add this pipe in the module for which your component belongs to
  • call this pipe in the html

Working stackblitz:

https://stackblitz.com/edit/angular-njqyal?file=src/app/pipe/translate.pipe.ts

So then after you make your pipe your html will look like so: {{mdValue.value | yourPipeName}}

  • Related