【问题标题】:Creating a custom structural directive创建自定义结构指令
【发布时间】:2017-05-24 10:58:57
【问题描述】:

我一周前开始学习 Angular2 和最新的 angular4,现在我需要创建一个自定义结构指令来显示其中的内容。

解释:我有一个数组的元素一对字符串让我们调用数组标题的n个元素的第一个元素和第二个描述 这是结果https://ibb.co/i23Dxa

(数组来自后端,我是通过mock数组文件来模拟的)

现在,如果我调用我需要创建的结构指令,我希望它显示我将在该调用下编写的内容

示例:

<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;
    }
}

谁能更好地向我解释如何进行?非常感谢。

【问题讨论】:

  • 你读过吗?

标签: angular directive


【解决方案1】:

让我解释一下 组件看起来像这样...

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>

【讨论】:

  • 我已经导入到 NgModule 上的 app.module.ts "GridComponent" 中,并且我已经导出它以使其对所有组件公开。然后在另一个组件上,我已经导入了 GridComponent,但没有找到我的网格,就像我没有在 app.module 上导入它一样,删除它编译很好,没有错误,但没有显示按钮(如果我们可以通过电子邮件会更好:fede.benedetti9@gmail.com,它会更快,我会用最终答案更新这个问题)谢谢,顺便说一句
  • 这是plunk,它只是为了向您展示我的文件并让您更好地理解我的问题您在互联网上阅读的解决方案已被弃用,因为现在使用 另外,我需要将一个项目传递给 ng-template,使用 let-item 我需要更好地理解指令是如何构建的,希望你能帮助我^^
  • “我在互联网上阅读的您的解决方案已弃用”,提供任何参考吗?
  • 我会发布我在下一个 cmets 中读到的内容,但现在,我需要帮助使用 ng-template 和自定义指令来做这件事 如果你觉得我身边有一些侵略性,我很抱歉,不应该是这样的Pm我,如果你愿意,我们会在那里谈^^
  • 不,有一些东西,你需要看看,模板已被弃用,应该使用 ng-template...但是你真正需要的是 ng-content...如果你了解区别在所有..
猜你喜欢
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多