来自组件的 Angular 4 调用指令方法

标签 angular angular-directive angular-components

我正在尝试构建一个结构指令,它将更改通过使用其选择器(静态)或通过调用其公共(public)方法(动态)调用的父 DOM 结构。

  • 在 html 模板中使用指令选择器可以正常工作 任何问题。

  • 我想弄清楚我们是否可以在不在模板中使用它并通过调用指令方法的情况下实现相同的效果。

我的指令.ts

@Directive({ selector: '[sampleDirective]' })

export class SampleDirective {
    ...
   constructor(..) {
        this.customDirective();
     }
  }
customDirective() {
    console.log('Inside customDirective()');
}

我的组件.ts

import { SampleDirective } from './my.directive';
...
@Component({
 selector: 'my-component',
 template: `<button (click)="click()"> Click Me </button>`
})
constructor() { }
..
click() {
  // call directive method here
}

我需要这个,因为我正在创建一个通用解决方案,以在运行时借助指令更改组件的 DOM 结构。

** 如有错字请忽略。抱歉,我不能在这里粘贴完整的代码

最佳答案

如果组件模板中没有指令,Angular 将不会处理它。使用 ng-container 标签,您不会以任何方式使模板困惑。要获取指令,请使用 @ViewChildren/@ViewChild 获取指令的实例:

@Component({
 selector: 'my-component',
 template: `<button (click)="click()"> Click Me </button>
            <ng-container sampleDirective></ng-container>`
})
@ViewChildren(SampleDirective) dirs;
constructor() { }
..
click() {
   this.dirs.first.customDirective();
  // call directive method here
}

关于来自组件的 Angular 4 调用指令方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45947596/

相关文章:

javascript - 计时器 - Angular 8 的计时器

Angular 2+ : Use component as input in another component

javascript - 使用 ocLazyLoad 在表中延迟加载

javascript - 如何将父组件中声明的 ng-template 中的变量传递给子组件/指令?

javascript - Angular 2 - 创建指令

Angular 4 - 将对象从一个组件传递到另一个组件(无父子层次结构)

html - 如何仅更改具有 oceanWP 主题的 WordPress 网站上 Logo 的主页 URL?

node.js - 满足条件时取消所有 Protractor 测试

angular - 错误 : Uncaught (in promise): PushNotifications does not have web implementation

angular - 错误 TS2687 : All declarations of 'observable' must have identical modifiers