我有一个包含内容的对话框和一个切换开关,供用户在两种语言之间进行选择。当用户在这些语言之间切换时,只需更改对话框的内容,而不影响应用程序语言。
尝试创建一个接受语言的管道,但它改变了我的整个应用程序语言。我预计只有对话的语言会改变。 注意:我使用的是 Angular 14。
// language.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LanguageService {
private dialogLanguage: string = 'en'; // Default language for dialog
constructor() { }
// Method to set the language for the dialog
setDialogLanguage(lang: string) {
this.dialogLanguage = lang;
}
// Method to get the current language for the dialog
getDialogLanguage() {
return this.dialogLanguage;
}
}
// dialog.component.ts
import { Component } from '@angular/core';
import { LanguageService } from 'path/to/language.service';
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.css']
})
export class DialogComponent {
constructor(private languageService: LanguageService) {}
// Method to get the content based on the selected language
getDialogContent() {
const lang = this.languageService.getDialogLanguage();
// Use language to fetch content dynamically
// For example, you can use switch cases or an object map to return content based on the language
switch (lang) {
case 'en':
return {
title: 'Dialog Title',
message: 'This is a message in English.'
};
case 'fr':
return {
title: 'Titre du dialogue',
message: 'Ceci est un message en français.'
};
default:
return {
title: 'Dialog Title',
message: 'This is a message in English.'
};
}
}
}