Angular i18n能否应用于三元运算符?条件字符串使用可行性咨询
Great question! You absolutely can use Angular i18n alongside ternary operators, and conditional strings like the ones in your example are fully supported for internationalization. Let’s break down the best ways to handle this scenario.
Option 1: Add i18n to the Container Element
Your initial code is already valid, but we can make it more maintainable by adding a custom message ID and description to clarify context for translators:
<h2 i18n="Action heading|Label for add/edit mode@@actionHeading"> {{ updateMode ? 'Edit' : 'Add' }} </h2>
When you run ng extract-i18n to generate translation files, Angular will detect both Edit and Add as possible values for this message. Your messages.xlf file will include entries for both strings, allowing you to translate them individually for each target language.
Option 2: Use $localize for Granular Control
If you want to manage each conditional string as a separate translation unit (useful if they need distinct contexts or descriptions), use Angular’s $localize function directly in the expression:
<h2> {{ updateMode ? $localize`:@@editAction:Edit` : $localize`:@@addAction:Add` }} </h2>
With this approach, running ng extract-i18n will create two separate entries in your translation file—one for Edit (with ID editAction) and one for Add (with ID addAction). This gives you full control over how each string is translated, which is helpful for more complex apps.
Key Notes
- Ensure your Angular project is properly configured for i18n (check
angular.jsonfor localization settings, and confirm@angular/localizeis imported if using Angular 9+). - After extracting translations, create language-specific files (e.g.,
messages.fr.xlffor French) and add your translated strings there. - Both methods work seamlessly with other conditional logic too, like
*ngIfblocks or switch statements—Angular’s i18n tooling can pick up dynamic text wherever it appears in templates.
内容的提问来源于stack exchange,提问作者tonis

