如何点击按钮切换ngx-timeago的语言(德语转西班牙语)
解决ngx-timeago的语言切换问题
没问题,我来帮你实现点击按钮切换德语和西班牙语的功能!其实你已经做了大部分准备工作了,只需要补充几个小步骤就能搞定:
步骤1:在组件中保存TimeagoIntl实例并添加切换逻辑
你需要把构造函数里的TimeagoIntl实例保存为组件的属性,这样才能在点击方法里调用它。同时添加一个变量跟踪当前语言,再写一个切换语言的方法:
import { Component } from '@angular/core'; import { strings as stringsDe } from 'ngx-timeago/language-strings/de'; import { strings as stringsEs } from 'ngx-timeago/language-strings/es'; import { TimeagoIntl } from 'ngx-timeago'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { // 保存TimeagoIntl实例,方便后续调用 private intl: TimeagoIntl; // 跟踪当前使用的语言 currentLang = 'es'; constructor(intl: TimeagoIntl) { this.intl = intl; // 初始化语言为西班牙语 this.intl.strings = stringsEs; this.intl.changes.next(); } name = 'Angular'; date = new Date(); // 切换语言的方法 toggleLanguage() { this.currentLang = this.currentLang === 'es' ? 'de' : 'es'; // 根据当前语言设置对应的字符串 this.intl.strings = this.currentLang === 'es' ? stringsEs : stringsDe; // 通知组件更新语言显示 this.intl.changes.next(); } }
步骤2:给模板按钮添加点击事件
修改你的模板,给按钮绑定刚才写的toggleLanguage方法,还可以让按钮文本随语言切换动态变化:
{{ date | timeago:live}} <div class="btn" (click)="toggleLanguage()"> {{ currentLang === 'es' ? '切换到德语' : '切换到西班牙语' }} </div>
原理说明
TimeagoIntl里的changes是一个Subject,当你调用next()时,会通知所有使用timeago管道的组件重新渲染,从而更新为新的语言文本。
这样点击按钮就能在德语和西班牙语之间来回切换啦!
内容的提问来源于stack exchange,提问作者phildev
相关产品推荐
相关产品推荐

