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>

继续阅读 30秒学会 Angular 片段 – Loader Component

It’s possible to take a template as @Input for a component to customize the render

@Component({
  template: `
    <nav>
      <ng-container *ngTemplateOutlet="template"></ng-container>
    </nav>
  `,
})
export class SiteMenuComponent  {
  @Input() template: TemplateRef<any>;
}
<site-menu [template]="menu1"></site-menu>

<ng-template #menu1>
  <div><a href="#">item1</a></div>
  <div><a href="#">item2</a></div>
</ng-template>

Note: ng-content should be used for most of the cases and it’s simpler and more declarative.
Only use this approach if you need extra flexibility that can’t be achieved with ng-content.

继续阅读 30秒学会 Angular 片段 – Passing template as an input

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>

继续阅读 30秒学会 Angular 片段 – Reusing code 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;
}

继续阅读 30秒学会 Angular 片段 – Accessing Enums in template

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

翻译自:https://www.30secondsofcode.org/angular/s/renaming-inputs-and-outputs

相关链接