Angular 4 call directive method from component

冷暖自知 提交于 2019-12-05 00:49:52

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
}

For calling directive method from component, you could use ViewChild decorator to locate directive instance on the page. Then by using the same you could access directive all props.

@ViewChild(SampleDirective) directive;
constructor() { }
..
click() {
  // call directive method here
  this.directive.customDirective()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!