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

查看:154
本文介绍了来自组件的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.

我的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天全站免登陆