【问题标题】:Instantiate component from a directive从指令实例化组件
【发布时间】:2016-05-15 17:31:09
【问题描述】:

我需要实现自定义日期选择器。
为此,我有 date-picker.directive 和 select-date.component(对话框窗口)。

我通过 html 中的属性附加指令并且可以处理事件。通过点击事件指令应该调用对话框窗口(它是我们的组件)。

<button class="btn" type="button" date-picker>

但是如何从指令中实例化 select-date.component 呢?
如何将新组件添加到 DOM 中?

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    如果您知道组件的类型,您可以将其注入指令中

    export class DatePickerDirective {
      constructor(private selectDateComponent:SelectDateComponent) {}
    }
    

    如果指令应该能够访问应用它的任何类型的组件,那么您可以使用How to access the Component on a Angular2 Directive 中解释的方法(另请参阅此问题https://github.com/angular/angular/issues/8277

    【讨论】:

    • Günter Zöchbauer,您的解决方案有助于获取现有组件的访问权限。是否可以创建一个新的组件实例并将其添加到 DOM 中?
    • Günter Zöchbauer,感谢您的帮助,但您的示例展示了如何从组件创建组件。当我想为 component from directive. 找到解决方案时
    猜你喜欢
    • 2020-05-29
    • 2020-05-25
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2021-08-09
    • 2017-09-24
    • 2017-09-30
    • 2019-01-07
    相关资源
    最近更新 更多