Angular i18nSelect Pipe

By Arvind Rai, February 13, 2024
This page will walk through Angular i18nSelect pipe example.
1. The i18nSelect pipe is a generic selector that displays the string that matches the current value.
2. The i18nSelect pipe is used as following.
{{ inputValue | i18nSelect : mapping }} 
inputValue : A string to be internationalized.
mapping : A mapping object of text to be displayed for different values of provided 'inputValue'.

3. Find the code snippet using i18nSelect pipe.
{{ selectedNumber | i18nSelect: {'1': 'One', '2': 'Two', '3': 'Three'} }} 
When the value of selectedNumber is '1', the output will be 'One' and
when the value of selectedNumber is '2', the output will be 'Two' and
when the value of selectedNumber is '3', the output will be 'Three' and
when the value of selectedNumber something else such as '5', the output will be empty string.

4. We can add other key in mapping that will output for other inputValue for which there is no value in mapping.
{{ selectedNumber | i18nSelect: {'1': 'One', '2': 'Two', '3': 'Three', 'other': 'invalid'} }} 
When the value of selectedNumber is '5', the output will be 'invalid'.

Complete Example

app.component.html
<h3>Example-1</h3>

<div>User Name : <b> {{ selectedPerson.gender | i18nSelect: {'male': 'Mr.', 'female': 'Miss'} }}
    {{selectedPerson.name}} </b> </div>

<h3>Example-2</h3>

<div>
  Selected Day: <b> {{ selectedDayId | i18nSelect: daysMap }} </b>
</div>

<h3>Example-3</h3>

<div>
  Number of Students: <b> {{ selectedNumber | i18nSelect: numberMap }} </b>
</div> 
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  //Example-1
  persons = [
    { name: 'Sita', gender: 'female' },
    { name: 'Ram', gender: 'male' }
  ];
  selectedPerson = this.persons[0];

  //Example-2
  daysMap = {
    '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday',
    '6': 'Saturday', '7': 'Sunday', 'other': 'Invalid Day'
  };
  selectedDayId = '3';

  //Example-3  
  numberMap = {
    '1': 'One', '2': 'Two', '3': 'Three', '4': 'Four', '5': 'Five', 'other': 'Invalid'
  };
  selectedNumber = '3';
} 
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { } 

Output

Find the print-screen of the output.
Angular i18nSelect Pipe

Reference

I18nSelectPipe

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us