Search code examples
angularangular-ui-routerdartangular-dart

Advantage to use Route instead *ngIf to control Angular View Component?


In the Tutorial Angular example it is used Route to select and control Angular View Component.

I know that we can to use the *ngIf directive to select a View. This way, I think that is more readable.

See the examples:

Route (like Tutorial)

template: '''
<h1>{{title}}</h1>
<nav>
  <a [routerLink]="['Dashboard']">Dashboard</a>
  <a [routerLink]="['Heroes']">Heroes</a>
</nav>
<router-outlet></router-outlet>
''',

...

@RouteConfig(const [
  const Redirect(path: '/', redirectTo: const ['Dashboard']),
  const Route(
    path: '/dashboard',
    name: 'Dashboard',
    component: DashboardComponent,
  ),
  const Route(
    path: '/detail/:id',
    name: 'HeroDetail',
    component: HeroDetailComponent,
  ),
  const Route(path: '/heroes', name: 'Heroes', component: HeroesComponent)
])

*ngIf (altenative to Route)

template: '''
  <h1>{{title}}</h1>
  <nav>
    <button on-click="optionMenu(1)">Dashboard</button>
    <button on-click="optionMenu(2)">Heroes</button>
  </nav>
  <div *ngIf="oMenu == 1">
    <my-dashboard></my-dashboard>
  </div>
  <div *ngIf="oMenu == 2">
    <my-heroes></my-heroes>
  </div>    
  '''
  ...

class AppComponent {   
  int oMenu;

  void optionMenu(int i) {
    oMenu = i;
  }
}

What are they the advantages to use the Angular Route strategy instead *ngIf?


Solution

  • The main advantage is that the browser URL bar reflects the state.

    When the user creates a bookmark and comes back, she will get the same view, while with *ngIf, the initial view will always be the same.

    A disadvantage using the router is, that no bindings like <my-component [foo]="xxx" (bar)="doSomething()" are not possible with components added by the router. For this kind of communication usually a shared service is used.