首页 文章

Angular 2动态html具有属性绑定

提问于
浏览
2

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

我想在html中使用名称绑定加载此字符串 . 我找到了一些像 [innerHTML] 这样的答案但是它没有绑定组件中声明的属性 .

1 回答

  • 0

    有想法实现它,如果我们为组件创建自定义注释并使用它我们可以从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 {
    }
    

相关问题