我有组件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
我怎样才能做到这一点?
谢谢
发布于 2017-07-20 12:39:44
我猜你在使用@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标记之间收集文本,并将其传递给将转换为@Input的childTmpl属性。
之后,您可以将ContentChild字符串输入
app-preview.component.ts
export class AppPreview {
@Input() childTmpl: string;
ngOnInit() {
console.log(this.childTmpl);
}
}如果您想要看到它的实际行动,那么请查看柱塞实例
如果你不知道做什么,就不要做它。
以查看角解析模板如何查看
发布于 2017-07-20 11:45:28
尝试添加对应用程序预览的引用。
<app-preview [title]="'PREVIEW'" [id]="'prev'" #test>
<checkbox #prv
[indeterminate]="true"
[checked]="true">
</checkbox>
</app-preview>在您的.ts文件中,您可以接收本地元素的内部HTML,并按您的意愿保存它:
@ViewChild('test') input:ElementRef;
ngAfterViewInit() {
console.log(this.input.nativeElement.innerHTML);
}不要忘记导入ElementRef和ViewChild。
https://stackoverflow.com/questions/45212368
复制相似问题