Home > Enterprise >  accessing to an object depending on given parameter
accessing to an object depending on given parameter

Time:07-13

I want to translate texts with Angular Pipe.

component.html

<div> {{ 'save' | translate : 'fr'}}  </div>

_

translate.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { findIndex } from 'rxjs';

@Pipe({
  name: 'translate'
})
export class TranslatePipe implements PipeTransform {
    //some other irrelevant code  
    dictionaryFr = 
        {
          user :"utilisateur",
          save : "enregistrer",
        }      
            
      transform(text: string, lang: string): string{
    
        if (lang=="fr") return this.dictionaryFr[text]; //Does not work
  
      }

error message

   Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ user: string; save: string; }'. No index signature with a parameter of type 'string' was found on type '{ user: string; save: string; }

Assumed, I get the text "save" as parameter. I would expect, that above code accesses to dictionaryEn.user and returns "enregistrer". Unfortunately that doesn't work. Why I cannot replace this.dictionaryEn['user'] with this.dictionaryEn[text], since "text" has as value "user".

How can I access to the dictionary depending on which text I get as parameter?

CodePudding user response:

Seems like a simple type issue, please refer the below code. I have defined the type where the object key will be a string and the value will also be a string!

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'translate',
})
export class TranslatePipe implements PipeTransform {
  //some other irrelevant code
  dictionaryFr: { [key: string]: string } = {
    user: 'utilisateur',
    save: 'enregistrer',
  };

  transform(text: string, lang: string): string {
    if (lang == 'fr') return this.dictionaryFr[text]; //Does not work
  }
}

stackblitz

  • Related