angular 2/4 将 ContentChild 模板保存为字符串

标签 angular

我有一个组件 app-preview,它有一个由它的父组件推送到它的 ng-content 中的组件。

app-preview父级的代码:

<app-preview>
      <checkbox #prv
        [indeterminate]="true"
        [checked]="true">
      </checkbox>
</app-preview>

我希望 app-preview 不仅要渲染,还要将任何组件的模板作为字符串保存到任何属性中 ng-content .所以我希望 app-preview 保存以下字符串:

  "<checkbox #prv
    [indeterminate]="true"
    [checked]="true">
  </checkbox>"

进入它的属性并在它的 .ts 文件中使用它。 例如:this.childTmpl

我怎样才能做到这一点?

谢谢

最佳答案

我猜你正在使用 @angular/compiler

因此在这种情况下,可以通过覆盖例如 I18NHtmlParser.parse 方法轻松完成:

import { Attribute as HtmlAttribute, I18NHtmlParser } from '@angular/compiler';

function visitAll(visitor: any, nodes: any[]): any[] {
  const result: any[] = [];
  nodes.forEach(ast => ast.visit(visitor));
  return result;
}

class MyVisitor {
  visitElement(ast: any) {
    if(ast.name === 'app-preview') {
      const text = ast.sourceSpan.start.file.content
             .substring(ast.startSourceSpan.end.offset, ast.endSourceSpan.start.offset);
      ast.attrs.push(new HtmlAttribute('childTmpl', text, ast.startSourceSpan))
    }
    visitAll(this, ast.children);
  }
  visitAttribute() {}
  visitText() {}
  visitComment() {}
}
const originParse = I18NHtmlParser.prototype.parse;
const visitor = new MyVisitor();
I18NHtmlParser.prototype.parse = function() {
  const result = originParse.apply(this, arguments);
  visitAll(visitor, result.rootNodes)
  return result;
};

它将收集 app-preview 标签之间的文本并将其传递给 childTmpl 属性,该属性将被转换为 @Input

之后就可以得到ContentChild字符串

app-preview.component.ts

export class AppPreview {
   @Input() childTmpl: string;

   ngOnInit() {
     console.log(this.childTmpl);
   }
}

如果您想看到它的实际效果,请查看 Plunker Example

P.S. 如果您不知道它的作用,请不要这样做。

看angular解析模板的样子

https://alexzuza.github.io/enjoy-ng-parser

关于angular 2/4 将 ContentChild 模板保存为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45212368/

相关文章:

javascript - ng2-translate (404 not found) 我已经在 system.js 中添加了

angular - 类型错误 : Cannot read property of undefined - but site works accurately - Angular 7

angular - 将 Observable 中的参数提供给返回 Observable 的函数

angular - 如何将值传递给 Angular Directive(指令)

Angular 2 : How to use observables to debounce window:resize

java - Whitelabel错误页面404 Spring Boot Angular 6

javascript - 单击 anchor 元素时页面重新加载

angular - 如何在 Angular 2的小数管道中使用变量

angular - 异步验证器 (AsyncValidatorFn) 从未订阅

Angular 5 Jasmine 错误 : Expected one matching request for criteria found none