我想手动编译一些包含HTML的指令.$compileAngular 2中的等价物是什么?
例如,在Angular 1中,我可以动态编译HTML片段并将其附加到DOM:
var e = angular.element('<div directive></div>');
element.append(e);
$compile(e)($scope);
Run Code Online (Sandbox Code Playgroud) 假设我有两个组成部分:parent和child.HTML将如下所示:
<parent title="Welcome">
<child name="Chris">Blue Team</child>
<child name="Tom">Red Team</child>
</parent>
Run Code Online (Sandbox Code Playgroud)
最终输出如下:
<h1>Welcome</h2>
<ul>
<li><b>Chris</b> is on the Blue Team</li>
<li><b>Tom</b> is on the Red Team</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
父组件:
@Component({
selector: 'parent',
directives: [ChildComponent], // needed?
template: `
<h1>{{title}}</h1>
<ul>
<li *ngFor="#child of children()">{{child.content}}<li>
</ul>`
})
export class ParentComponent {
@Input() title;
children() {
// how?
}
}
Run Code Online (Sandbox Code Playgroud)
如何从父级中访问子组件并获取其内容?
此外,我不希望自动渲染孩子.根据某些条件,我可能会选择不显示某些孩子.
谢谢.
我试图将transcluded内容绑定到组件循环内部的变量,但我无法这样做.
我查看了PrimeNG的dropdown组件,他们一起使用template标签let-car绑定到car循环的变量.
但是,当我尝试这个时,我甚至无法将内容转换为内容.实现这一目标的正确方法是什么?
尝试:
<!-- Obviously not gonna work -->
<comp>
<span>{{option.name}}, {{option.type}}</span>
</comp>
<!-- Thought this would work but it doesn't, in odd scenarios I get the last element of the loop to transclude content and bind correctly. -->
<comp>
<template let-option>
<span>{{option.name}}, {{option.type}}</span>
</template>
</comp>
Run Code Online (Sandbox Code Playgroud)
在组件中:
<ul>
<li *ngFor="let option of options">
<ng-content></ng-content>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
简单的我正在努力实现的目标:
所以我有一个组件 <template>
<some-component [data]="someArray">
<template>foo<template>
</some-component>
Run Code Online (Sandbox Code Playgroud)
并且它正在使用它来获取模板
@ContentChild(TemplateRef)
public tmpl: TemplateRef<any>;
Run Code Online (Sandbox Code Playgroud)
然后在它的模板中使用它
<div *ngFor="let item of someArrayFromDataInput">
<template [ngTemplateOutlet]="tmpl"></template>
</div>
Run Code Online (Sandbox Code Playgroud)
现在我希望能够从item原始模板中打印一些数据,基本上能够做到这一点
<some-component [data]="someArray">
<template>foo {{ item }}<template>
</some-component>
Run Code Online (Sandbox Code Playgroud)
有可能吗?
<div class="main">
<ng-content select="[body]"></ng-content>
</div>
<div class="main-copy">
<ng-content select="[body]"></ng-content>
</div>
Run Code Online (Sandbox Code Playgroud)
我试图将相同的内容复制到主副本,但遗憾的是它无法正常工作.
有什么建议吗?