【发布时间】:2023-03-26 01:05:01
【问题描述】:
我正在构建一个 Angular 9 应用程序。 在这个应用程序中,我让我的用户以文本形式将“占位符”保存到数据库中。
我想呈现这些占位符,但在渲染时将其替换为真实数据。
例如。保存数据的对象称为模型,所以通常我会在页面上显示这样的数据,显示用户名。
{{model.fullname}}
基本上我想将这个占位符保存到数据库中,然后渲染它。所以我的问题是如何让 {{model.fullname}} 在呈现页面时“激活”,即使它来自数据库/JSON 而不是硬编码到页面中。
更新
我尝试了下面发布的 Pipe 建议,它确实有效。问题是它单独打印真实数据,而不是在较大字符串内的上下文中。换句话说,我需要将文本中的占位符值替换到它们在字符串中的真实位置。
这是管道代码:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'template',
})
export class TemplatePipe implements PipeTransform {
transform(value: string, args: any): any {
if (value.indexOf('.name') !== -1) {
return args.name;
}
if (value.indexOf('.id') !== -1) {
console.log(args.id);
return args.id;
}
return null;
}
}
这是我想使用的典型文本:
The name of the user is {{model.name}} and got the ID of {{model.id}}.
结果必须是:
The name of the user is Paul Palmer and got the ID of 123456.
【问题讨论】:
-
这能回答你的问题吗? stackoverflow.com/q/34784778/1260204
-
谢谢,但看起来不像。我不想动态渲染组件,而只想渲染小变量。
标签: angular