【问题标题】:Angular 2 dynamic html with properties binding具有属性绑定的 Angular 2 动态 html
【发布时间】:2016-12-07 14:06:48
【问题描述】:

我有一个 html 字符串来自像 html='<span>{{name}}</span>' 这样的数据库,其中名称是组件上的一个属性。

我想用名称绑定在 html 中加载这个字符串。我找到了一些答案,例如[innerHTML],但这并没有绑定组件中声明的属性。

【问题讨论】:

  • 你会在这里得到相同的答案 ;-) 你可以在运行时创建组件(你失去了 AoT),就像stackoverflow.com/questions/34784778/…中解释的那样
  • 感谢您的快速回答,但我不想创建一个组件,我只会在单击按钮时收到一个字符串有什么办法吗?
  • 当然,创建一个组件,使用该字符串作为模板,然后就可以了。您将获得 Angular2 与运行时提供的字符串的绑定。没有组件就没有办法。 Angular2 绑定仅适用于组件模板。

标签: angular


【解决方案1】:

如果我们为组件创建自定义注释并使用它,我们可以从 api 中获取元数据,例如从 jsp 文件中获取元数据并将其添加到模板而不是 templateUrl

我还没有创建示例代码,但粗略的想法在这里 ->

    export function CustomComponent(annotation: any) {
      return function (target: Function) {
// call your database and get your string here
        var parentTarget = Object.getPrototypeOf(target.prototype).constructor;

        var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);

        var parentAnnotation = parentAnnotations[0];
        Object.keys(parentAnnotation).forEach(key => {
          if (isPresent(parentAnnotation[key])) {
            if (!isPresent(annotation[key])) {
              annotation[key] = parentAnnotation[key];
            }
          }
        });

        var metadata = new ComponentMetadata(annotation);

        Reflect.defineMetadata('annotations', [ metadata ], target);
      };
    };

并像使用它

@CustomComponent({
  selector: 'sub'
})
export class SubComponent {
}

【讨论】:

    猜你喜欢
    • 2017-09-20
    • 1970-01-01
    • 2022-06-28
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多