AngularJS

Angular Material: No Instance Found For Handle Left

This is the error. “No instance found for handle left”. I’ve been allowing it to run rampant there for a while now due to tight schedule. Now that there’s a bit of extra time.. Let’s murder it.

 white line

Sniffing Around

Tracing the error in console, it’s triggered by this line of code:

$mdSidenav('left').close();

Logging $mdSidenav out, we could trace back to this function:

return function(handle) {
  var self;
  var errorMsg = "SideNav '" + handle + "' is not available!";
  var instance = $mdComponentRegistry.get(handle);

  if(!instance) {
     $mdComponentRegistry.notFoundError(handle);
  }

  return self = {
    isOpen: function() {...},
    isLockedOpen: function() {...},
    toggle: function() {...},
    open: function() {...},
    close: function() {...},
    then : function( callbackFn ) {...}
  };
};

My guess is that the instance hasn’t initialised yet upon the close() call. And looking at the definition of notFoundError, bingo:

notFoundError: function(handle) {
  $log.error('No instance found for handle', handle);
}

Strangely, there isn’t a method to check if an instance of mdSidenav has initialised or not without puking error logs all over the place. There is however, a way to work around it. At the bottom of the $mdSidenav function, after returning the self object, these lines of code innocently sit there:

/**
* Deferred lookup of component instance using $component registry
*/
function waitForInstance() {
  return $mdComponentRegistry
    .when(handle)
    .then(function(it){
      instance = it;
      return it;
    });
}

Make good use of them.

 

Solution

Use this instead:

$mdComponentRegistry.when('left').then(function(leftSidenav){
  leftSidenav.close();
});
Standard