Angular 4 method of specifying a call from a component

I am trying to create a structural directive that will change the parent structure of the DOM invoked using its selector (static) or by calling its public method (dynamic).

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

  • I am trying to figure out if we can achieve this without using it in the template and 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
}

I need this because I am creating a general solution for changing the structure of the DOM component at runtime using the directive.

** Please ignore if there is a typo. sorry i couldn't paste the full code here

+4
2

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
}
+5

ViewChild decorator, . , , .

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

Source: https://habr.com/ru/post/1684698/


All Articles