Search code examples
angulartypescriptangular-directive

Angular: Call method from directive in component


i am trying to call method from directive. Lets say i have directive myDirective.ts

@Directive({
  selector: '[something]',
})
export class myDirective implements OnInit {
....
public myMethod(){
console.log(it works)
}
....
}

and component.ts (this is what i found but on this.directive i get error object is possibly null)

@Component({
  selector: '...',
  templateUrl: '....html',
  styleUrls: ['....css'],
})
export class MyComponent implements OnInit {
  @ViewChild(myDirective) directive = null

  ngOnInit() {
  }

  onClickFunction() {
    return (
      this.directive.myMethod();
    );
  }
}

How can i call this method in component?


Solution

  • Just run like this

    @Component({
      selector: '...',
      templateUrl: '....html',
      styleUrls: ['....css'],
    })
    export class MyComponent implements OnInit {
      @ViewChild(myDirective) directive;
    
      ngOnInit() {
      }
    
      onClickFunction() {
        return (
          this.directive?.myMethod()
        );
      }
    }
    

    In tsconfig.json add

    "strictPropertyInitialization":false,