You can use advanced property bindings to set specific style values based on component property values:

<p [style.background-color]="'green'">
  I am in green background
</p>

<p [style.font-size.px]="isImportant ? '30' : '16'">
  May be important text.
</p>

继续阅读 30秒学会 Angular 片段 – Style bindings

Sometimes we need to work with every single Control is a form. Here’s how it can be done:

function flattenControls(form: AbstractControl): AbstractControl[] {
  let extracted: AbstractControl[] = [ form ];
  if (form instanceof FormArray || form instanceof FormGroup) {
    const children = Object.values(form.controls).map(flattenControls);
    extracted = extracted.concat(...children);
  }
  return extracted;
}

For examples use:

// returns all dirty abstract controls
flattenControls(form).filter((control) => control.dirty);

// mark all controls as touched
flattenControls(form).forEach((control) => 
    control.markAsTouched({ onlySelf: true }));

继续阅读 30秒学会 Angular 片段 – Accessing all nested form controls

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

When having a separate routing module, instead of creating an NgModule you can export router configuration directly:

export const AppRoutingModule = RouterModule.forRoot(routes, config);

or

export const FeatureRoutingModule = RouterModule.forChild(routes);

and use it in your module

@NgModule({
  imports: [
    ...
    AppRoutingModule,
    ...
  ]
})

翻译自:https://www.30secondsofcode.org/angular/s/router-module

相关链接

It is possible to execute asynchronous task before the app start by providing a function returning promise using APP_INITIALIZER token.

@NgModule({
  providers: [
    {
      provide: APP_INITIALIZER,
      useValue:  functionReturningPromise
      multi: true
    },
})
export class AppModule {}

继续阅读 30秒学会 Angular 片段 – Using APP_INITIALIZER to delay app start

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

The Safe Navigation Operator helps with preventing null-reference exceptions in component template expressions. It returns object property value if it exists or null otherwise.

<p> I will work even if student is null or undefined: {{student?.name}} </p>

继续阅读 30秒学会 Angular 片段 – Safe Navigation Operator