Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally insert/remove host DOM element in angular 2 directive

I want to create a directive that will decide whether should or should not its host element apppear on the page. Ideally I would like it to remove the element from the DOM and not just hide/show it with css. Usecase is:

<ul role="navigation">
  <li><a>public link</a></li>
  <li><a>public link2</a></li>
  <li access="admin"><a>admin-only link</a></li>
</ul>

It would use UserService to get currentUser roles and if there's no admin there the li would be removed.

I suppose I could achieve the same effect with ng-if (if it's still available in angular 2) by passing the expression to evaulate in the main component. But with the directive it is more semantic and elegant.

Is it possible?

import {Directive} from 'angular2/angular2';

@Directive({
    selector: 'access'
})
export class Access {
 //what goes here
}

I could've easily done that in angular 1 (inside directive's compile function), but how can I do this in Angular 2?

like image 698
dKab Avatar asked Dec 24 '15 07:12

dKab


1 Answers

This implementation will be similar to what ngIf directive is. And the Angular guide for structural directives (which you plan to create too) gives an example of myUnless that just reverses ngIf.

You implementation for access will look similar to the myUnless implementation.

@Directive({ selector: '[access]' })
export class AccessDirective {
  constructor(
    private _templateRef: TemplateRef,
    private _viewContainer: ViewContainerRef
  ) { }
  @Input() set myUnless(condition: boolean) {
    if (condition) {
      this._viewContainer.createEmbeddedView(this._templateRef);
    } else {
      this._viewContainer.clear();
    }
  }
}

And use it like:

<li *access="isAdmin"><a>admin-only link</a></li>
like image 94
Chandermani Avatar answered Sep 18 '22 13:09

Chandermani