Michaelo
Michaelo

Reputation: 839

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?

Upvotes: 3

Views: 1002

Answers (1)

Abhishek Priyadarshi
Abhishek Priyadarshi

Reputation: 581

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,

Upvotes: 2

Related Questions