【问题标题】:instantiate angular custom directive from angular component on click单击时从角度组件实例化角度自定义指令
【发布时间】:2020-07-19 06:50:51
【问题描述】:

假设我有一个名为“my-custom-directive”的指令和一个名为“app.component”的组件 我在 app.component 中有一个方法 - createDirective() 将在单击 app-component.html 中的按钮时调用 我想用这个方法实例化 my-custom-directive。 如何在 angular2 及以上版本中做到这一点?

我尝试使用 Renderer2 但无法从组件创建指令

【问题讨论】:

  • 假设一切都很好,但代码示例更好。你能展示一下你目前拥有的东西吗

标签: angular angular-directive angular-components angular-custom-validators


【解决方案1】:
import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[my-custom-directive]'
})
export class MyCustomDirective {

  constructor() { }

  @HostListener('click', ['$event']) onClick($event: Event) {
    // Do what ever you want to do ....
  }
}

// In Your Component HTML : 
<button my-custom-directive></button>

// Don't forget to include the references in your Module.
// See if this Solves your purpose. 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多