I want to access NgbDropdown methods from service outside of the component. Here is the template snippet:
<div ngbDropdown #dropDown="ngbDropdown" display="static">
<a ngbDropdownToggle (click)="$event.preventDefault()" href="#" role="button" id="dropdownMenuButton">
Actions
</a>
<div ngbDropdownMenu aria-labelledby="dropdownManual">
<button ngbDropdownItem>Action - 1</button>
<button ngbDropdownItem>Another Action</button>
<button ngbDropdownItem>Something else is here</button>
</div>
</div>
In my Component I can easily access NgbDropdown's method by using template reference. For example:
@ViewChild('dropDown', {static: true}) dropDown: NgbDropdown;
...
...
someMethod() {
this.dropDown.toggle(); // toggle method from NgbDropdowm.
}
But in my case, I have to use that toggling operation from service (not in component). How can I achieve that?
My service:
export class Service{
constructor() {}
// some operation happened after clicking button from dropdown menu
doStuff() {
doSomeOtherStuff();
...
// after completing work I want to close/toggle the dropdown. Not before
// here will be the code of closing dropdown
}
}
You can pass the dropdown to the method of the service
this.myService.doStuff(this.dropDown)
Or, declare a variable in your service "dropDown", and in AfterViewInit of the component equal the variable of the service
ngAfterViewInit()
{
this.myService.dropDown=this.dropDown
}