Jerry's Blog

Recording what I learned everyday

View on GitHub


21 June 2019

Angular (8) -- Directives

by Jerry Zhang

Day 17:

Building our own structural directives

import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';

@Directive({
  selector: '[appUnless]'
})
export class UnlessDirective {
  @Input() set appUnless(condition: boolean) {
    if (!condition) {
      this.vcRef.createEmbeddedView(this.templateRef);
    } else {
      this.vcRef.clear();
    }
  }

  constructor(private templateRef: TemplateRef<any>, private vcRef: ViewContainerRef) { }

}
<div *appUnless="onlyOdd">
  <li
    class="list-group-item"
    [ngClass]="{odd: even % 2 !== 0}"
    *ngFor="let even of evenNumber">
    
  </li>
</div>

ngSwitch

value = 5;
<div [ngSwitch]="value">
    <p *ngSwitchCase="5">Value is 5</p>
    <p *ngSwitchCase="10">Value is 10</p>
    <p *ngSwitchCase="100">Value is 100</p>
    <p *ngSwitchDefault>Value is Default</p>
</div>

Tip: Should not use bootstrap dropdown. Only use Angular to manipulate the DOM.

Listen to the click event from the whole document

@HostListener('document:click', ['$event']) toggleOpen(event: Event) {
    this.isOpen = this.elRef.nativeElement.contains(event.target) ? !this.isOpen : false;
}

Tip: Version Compatibility

When I use the project from online, Angular requires a lower version of typescript. So I used my own project and add the new components into my own project.

I think it should also be working if I install a lower version of typescript.

After all, Angular’s npm dependencies are usually huge.

tags: Angular