简体   繁体   English

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

[英]Angular 4 call directive method from component

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). 我正在尝试构建一个结构指令,它将通过使用其选择器(静态)或通过调用其公共方法(动态)来调用父DOM结构。

  • Using the directive selector in a html template works fine without any issues. 在html模板中使用指令选择器可以正常工作而不会出现任何问题。

  • 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.ts

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

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

my-component.ts 我-component.ts

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

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. 我需要这个,因为我正在创建一个通用的解决方案,在运行时借助指令更改组件的DOM结构。

** please ignore if there are any typo. ** 如果有任何拼写错误,请忽略。 sorry that i couldn't paste the complete code here 抱歉,我无法在此处粘贴完整代码

If there's no directive in the component template Angular won't process it. 如果组件模板中没有指令,Angular将不会处理它。 With ng-container tag you will not clutter template in any way. 使用ng-container标签,您不会以任何方式混淆模板。 To get the directive then use @ViewChildren/@ViewChild to get the instance of the directive: 要获取该指令,请使用@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
}

For calling directive method from component, you could use ViewChild decorator to locate directive instance on the page. 要从组件调用指令方法,可以使用ViewChild装饰器在页面上定位指令实例。 Then by using the same you could access directive all props. 然后通过使用相同的,您可以访问指令所有道具。

@ViewChild(SampleDirective) directive;
constructor() { }
..
click() {
  // call directive method here
  this.directive.customDirective()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM