rangle / angular-training-examples

Blog application for Angular 2 training
13 stars 21 forks source link

Code examples are not always following Angular 2 style guide #15

Closed barretodavid closed 8 years ago

barretodavid commented 8 years ago

I have detected some inconsistencies between the code examples and the official style guide. Here are my findings and suggestions:

Filenames

component-1.ts

@Component({
  selector: 'component-1',
  template: 'Component 1',
})
export class Component1 {}

Do:

first.component.ts

@Component({
  selector: 'rio-first',
  template: 'First Component',
})
export class FirstComponent {}

Imports

 import { AppComponent } from './app.component';
 import { ChildComponent } from './child.component';

Selectors

There's not an official recommendation about this, but every example that I see in angular.io declare the properties of the NgModule decorator in this order:

@NgModule({
  imports: [],
  providers: [],
  declarations: [],
  exports: [],
  bootstrap: []
})

This is just a recommendation but having the imports at the top and exports at the bottom (for feature modules) is similar to the order we have in a normal ES6 module. Also having declarations close to exports makes it easy to spot which elements are public or private to the module.

Routing Module

The Angular team is now recommending of creating a separate modules for routes. So instead of having a file like this:

routes.ts

import { Routes } from '@angular/router';
import { Component1 } from './component-1';
import { Component2 } from './component-2';

export const routes: Routes = [
  { path: '', redirectTo: 'component-1', pathMatch: 'full' },
  { path: 'component-1', component: Component1 },
  { path: 'component-2', component: Component2 },
  { path: '**', component: Component1 },
];

Do:

app-routing.module.ts

import { NgModule }     from '@angular/core';
import { RouterModule } from '@angular/router';

import { FirstComponent } from './first.component';
import { SecondComponent } from './second.component';

@NgModule({
  imports: [
    RouterModule.forRoot([
      { path: '', redirectTo: 'first', pathMatch: 'full' },
      { path: 'first', component: FirstComponent },
      { path: 'second', component: SecondComponent },
      { path: '**', component: FirstComponent },
    ])
  ],
  exports: [
    RouterModule,
  ],
})
export class AppRoutingModule {}

And then in your root module:

...
@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  ...
})
export class AppModule {}

Others