Angular i18nSelect Pipe
December 29, 2021
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 }}
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'} }}
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'} }}
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>
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'; }
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 { }
Run Application
To run the application, find the steps.1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Run ng serve using command prompt.
4. Access the URL http://localhost:4200
Find the print screen of the output.
