创建自定义结构指令
Creating a custom structural directive
一周前我开始学习 Angular2 和最新的 angular4,现在我需要创建一个自定义结构指令来显示其中的内容。
解释:我有一对字符串数组的一个元素让我们调用数组标题的 n 个元素的第一个元素和第二个描述
这是结果 https://ibb.co/i23Dxa
(数组来自后端,我是通过模拟数组文件模拟的)
现在,如果我调用我需要创建的结构指令,我希望它显示我将在该调用下编写的内容
示例:
<ng-template aulos-configuration-item-toolbar>
<button (click)="click()">just click</button>
</ng-template>
这应该只呈现我在标签之间写的按钮,现在,我有这个:
import { Directive, Input, TemplateRef, ViewContainerRef } from "@angular/core";
@Directive({
selector: "[aulos-configuration-item-toolbar]",
})
export class AulosConfigurationItemToolbar {
public templateRef: TemplateRef<any>;
constructor(templateRef: TemplateRef<any>) {
this.templateRef = templateRef;
}
}
有人可以更好地向我解释如何继续吗?非常感谢。
让我解释一下
组件看起来像这样...
export class GridOptionsComponent { }
@Directive({ selector: 'grid-options' })
@Component({
selector: 'my-grid',
moduleId: module.id,
templateUrl: './grid.component.html'
})
export class GridComponent {
....
....
}
grid.component.html 长得像
<div class="col-md-3">
<div> some more html elements, components </div>
<ng-content select="grid-options"></ng-content>
</div>
并且在另一个组件中的用法应该是
<my-grid>
<grid-options>
<button >Add</button>
<button >View</button>
</grid-options>
</my-grid>
一周前我开始学习 Angular2 和最新的 angular4,现在我需要创建一个自定义结构指令来显示其中的内容。
解释:我有一对字符串数组的一个元素让我们调用数组标题的 n 个元素的第一个元素和第二个描述 这是结果 https://ibb.co/i23Dxa
(数组来自后端,我是通过模拟数组文件模拟的)
现在,如果我调用我需要创建的结构指令,我希望它显示我将在该调用下编写的内容
示例:
<ng-template aulos-configuration-item-toolbar>
<button (click)="click()">just click</button>
</ng-template>
这应该只呈现我在标签之间写的按钮,现在,我有这个:
import { Directive, Input, TemplateRef, ViewContainerRef } from "@angular/core";
@Directive({
selector: "[aulos-configuration-item-toolbar]",
})
export class AulosConfigurationItemToolbar {
public templateRef: TemplateRef<any>;
constructor(templateRef: TemplateRef<any>) {
this.templateRef = templateRef;
}
}
有人可以更好地向我解释如何继续吗?非常感谢。
让我解释一下 组件看起来像这样...
export class GridOptionsComponent { }
@Directive({ selector: 'grid-options' })
@Component({
selector: 'my-grid',
moduleId: module.id,
templateUrl: './grid.component.html'
})
export class GridComponent {
....
....
}
grid.component.html 长得像
<div class="col-md-3">
<div> some more html elements, components </div>
<ng-content select="grid-options"></ng-content>
</div>
并且在另一个组件中的用法应该是
<my-grid>
<grid-options>
<button >Add</button>
<button >View</button>
</grid-options>
</my-grid>