如何实现支持区域本地化的Angular Yes/No布尔管道
Angular 本地化Yes/No布尔管道实现
实现目标:使用体验对齐Angular内置date管道,支持传入区域参数返回对应语言的“是/否”文本,无额外依赖。
用法示例
和内置管道参数逻辑一致,区域参数可选,不传则默认读取应用全局配置的区域标识:
<!-- 指定德语区域,返回Ja/Nein --> {{ my.boolean | yesNo : "de-DE" }} <!-- 不传参走全局默认区域,简体中文环境返回是/否,英文环境返回Yes/No --> {{ my.boolean | yesNo }}
完整实现代码
核心逻辑优先用浏览器原生Intl.DisplayNames API获取标准本地化文本,低版本环境走内置兜底映射,标记为纯管道保证和内置管道一致的性能表现:
import { Pipe, PipeTransform, LOCALE_ID, inject } from '@angular/core'; @Pipe({ name: 'yesNo', pure: true }) export class YesNoPipe implements PipeTransform { private readonly defaultLocale = inject(LOCALE_ID); // 低版本环境兜底文本映射 private readonly fallbackTextMap: Record<string, { yes: string; no: string }> = { 'zh': { yes: '是', no: '否' }, 'zh-CN': { yes: '是', no: '否' }, 'en': { yes: 'Yes', no: 'No' }, 'en-US': { yes: 'Yes', no: 'No' }, 'de': { yes: 'Ja', no: 'Nein' }, 'de-DE': { yes: 'Ja', no: 'Nein' }, 'fr': { yes: 'Oui', no: 'Non' }, 'ja': { yes: 'はい', no: 'いいえ' }, 'ko': { yes: '예', no: '아니요' } }; transform(value: boolean, locale?: string): string { if (typeof value !== 'boolean') return ''; const activeLocale = locale || this.defaultLocale; try { // 现代浏览器原生支持,覆盖95%以上用户场景 const booleanFormatter = new Intl.DisplayNames([activeLocale], { type: 'boolean' }); return value ? booleanFormatter.of('true') as string : booleanFormatter.of('false') as string; } catch { // 兼容逻辑:匹配兜底字典,匹配失败默认返回英文 const matched = this.fallbackTextMap[activeLocale] || this.fallbackTextMap['en']; return value ? matched.yes : matched.no; } } }
配套配置
和date管道共用全局区域配置,在应用启动入口注册区域数据即可:
// app.config.ts(Standalone项目示例) import { ApplicationConfig, LOCALE_ID } from '@angular/core'; import { registerLocaleData } from '@angular/common'; import localeZhCn from '@angular/common/locales/zh-Hans'; // 注册简体中文区域数据 registerLocaleData(localeZhCn); export const appConfig: ApplicationConfig = { providers: [ // 配置全局默认区域为简体中文 { provide: LOCALE_ID, useValue: 'zh-CN' } ] };
如果是NgModule项目,在AppModule的providers数组里添加相同的LOCALE_ID配置即可。
内容的提问来源于stack exchange,提问作者Schmetti
相关产品推荐
相关产品推荐

