30 seconds of angular
Star
✨✨ New to Angular? Check out interactive Angular Codelab ✨✨

Accessing Enums in template

Enums are great but they are not visible in Angular templates by default.
With this little trick you can make them accessible.

enum Animals {
      DOG,
      CAT,
      DOLPHIN
    }
    
    @Component({
      ...
    })
    export class AppComponent {
      animalsEnum: typeof Animals = Animals;
    }
    

Loader Component

You can create own helper component and use it instead of *ngIf.

@Component({
      selector: 'loader',
      template: `
        <ng-content *ngIf="!loading else showLoader"></ng-content>
        <ng-template #showLoader>🕚 Wait 10 seconds!</ng-template>
      `
    })
    class LoaderComponent {
      @Input() loading: boolean;
    }
    

For usage example:

<loader [loading]="isLoading">🦊 🦄 🐉</loader>
    

Note that the content will be eagerly evaluated, e.g. in the snippet below destroy-the-world will be created before the loading even starts:

<loader [loading]="isLoading"><destroy-the-world></destroy-the-world></loader>
    

Links

Renaming inputs and outputs

In certain cases @Input and @Output properties can be named differently than the actual inputs and outputs.

<div 
      pagination 
      paginationShowFirst="true"
      (paginationPageChanged)="onPageChanged($event)">
    </div>
    
@Directive({ selector: '[pagination]'})
    class PaginationComponent {
      @Input('paginationShowFirst') 
      showFirst: boolean = true;
    
      @Output('paginationPageChanged') 
      pageChanged = new EventEmitter();
    }
    

Note: Use this wisely, see StyleGuide recommedation

Links

Reusing code in template

While the best way of reusing your code is creating a component, it's also possible to do it in a template.

To do this you can use ng-template along with *ngTemplateOutlet directive.

<p>
      <ng-container *ngTemplateOutlet="fancyGreeting"></ng-container>
    </p>
    
    <button>
      <ng-container *ngTemplateOutlet="fancyGreeting"></ng-container>    
    </button>
    
    <ng-template #fancyGreeting>
      Hello <b>{{name}}!</b>
    </ng-template>
    

Links

ngIf else

*ngIf directive also supports else statement.

<div *ngIf="isLoading; else notLoading">loading...</div>
    
    <ng-template #notLoading>not loading</ng-template>