来自组件的 Angular 4 调用指令方法 [英] Angular 4 call directive method from component

查看:37
本文介绍了来自组件的 Angular 4 调用指令方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i'm trying to build a structural directive that will change the parent DOM structure either invoked by using its selector (static) or by calling its public method(dynamic).

  • 在 html 模板中使用指令选择器可以正常工作,而无需任何问题.

  • Using the directive selector in a html template works fine without any issues.

我想弄清楚我们是否可以在不使用模板和调用指令方法的情况下实现相同的效果.

I'm trying to figure out if we an achieve the same without using it in template and by calling the directive method.

my-directive.ts

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

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

my-component.ts

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

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

I need this because i'm creating a generic solution to change the DOM structure of a component at runtime with help of a directive.

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

推荐答案

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

If there's no directive in the component template Angular won't process it. With ng-container tag you will not clutter template in any way. To get the directive then use @ViewChildren/@ViewChild to get the instance of the directive:

@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 调用指令方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆