I am trying to implement one standard where all string files are from separate constant files. Everything works great, but facing difficult when dynamic values in string occurs. Kindly help me how to use the constants.
constant.ts
export enum testPageConstants {
SuccessMessage = 'You have created {{count}} users'
}
userPage.ts
export class UserPage {
import {testPageConstants} from '...';
constantUIBind: typeof testPageConstants;
count = 10;
constructor() {
this.constantUIBind = testPageConstants;
}
}
userPage.html
<p> {{constantUIBind.SuccessMessage}}</p>
Output: In HTML am receiving like 'You have created {{count}} users' but I want like 'You have created 10 users
String Interpolation is a one-way databinding technique which is used to output the data from a TypeScript code to HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view.
How do I add spaces to a string interpolation? You can use string interpolation by using template literals; replace the quotes with backticks(`)(https://www.computerhope.com/jargon/b/backquot.htm).
Interpolation refers to embedding expressions into marked up text. By default, interpolation uses the double curly braces {{ and }} as delimiters.
In Angular, String interpolation is used to display dynamic data on HTML template (at user end). It facilitates you to make changes on component. ts file and fetch data from there to HTML template (component.
Another option is to create a pipe that will interpolate the string for you.
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "interpolate"
})
export class InterpolatePipe implements PipeTransform {
transform(value: any, args: any) {
value = value.replace(/{{([^}}]+)?}}/g, ($1, $2) =>
$2.split(".").reduce((p, c) => (p ? p[c] : ""), args)
);
return value;
}
}
and in the template:
<p>{{constantUIBind.SuccessMessage | interpolate:this}}</p>
The limitation here is that it can't interpolate objects like test.test
You can check the stackblitz here.
Inspiration from: https://stackoverflow.com/a/45235190/5613720
I am not sure if that is possible using enums
though one possible workaround could be yby wrapping your literals into functions
so change your enum to class like
class testPageConstants {
static SuccessMessage = (count)=>`You have created ${count} users`
}
then create a function to render like
render(template, data) {
return template(data);
}
then on ui
<p> {{render(constantUIBind.SuccessMessage,count)}}</p>
demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With