我有一个组件 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解析模板的样子
关于angular 2/4 将 ContentChild 模板保存为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45212368/