TODO List Project Part I - Use Angular to build FrontEnd II

previous_step

Build Angular Components for Frond-End

Step 1 : Welcome Component

  • Creating components using Angular CLI: ng generate component welcome. Note there is not rolling back, so make sure the name is correct before press enter!
  • The WelcomeComponent has been automatically declared in app.module.ts file. Note every Angular Component (@Component) is associated with NgModule (@NgModule).

Step 2: Login Component

  • Creating components using Angular CLI: ng generate component login.
  • Understanding Event Binding: Adding click event on Login Page.
    Event binding is like <button (event)=whatShouldYouDo()>Login</button>
  • \{\{\}\}: take the data from component to view
  • ngModel: banana-in-a-box-approach, do data binding from both sides. In order to enable ngModel, we need to import { FormsModule } from '@angular/forms in App.module.ts and add FormsModule in imports array. Code is as follows:
CLICK ME
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { LoginComponent } from './login/login.component';

@NgModule({
  declarations: [
    AppComponent,
    WelcomeComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Tips: Data Binding Approaches

  • Interpolation: tie a property to a view element
  • Event binding: bind a event with a component event
  • Two-way data binding: [(ngModel)]=propertyName

Step 3: Adding hardcoded authentication

The logic component used in Angular, i.e. *ngIf='invalidLogin'

Step 4: Implementing Routes for Login, Welcome and Error Message

  • Declear path const in app-routing.module.ts.
  • Add router-outlet tag in app.component.html.

Step 5: Creating an error component

Adding path to error page.
{ path: '**', component: ErrorComponent }

Step 6: Implementing Routing from Login to Welcome Component

In file login.component.ts, we want to use the Angular Router to let us redirect from the current login page to welcome page.
Then we can make use of dependency injection.

  • The concept of dependency injection is basically that if I need something, I should declear it as a dependency and Angular will make sure that depency would be given to us.
  • In Angular, dependency injection is a built-in feature, so we don’t need to add any lib.
  • If we want to get the dependency, we need to declare it as a constructor.
  • Every variable decleared in the constructor will be the member varialbe of this component automatically.

For example, in java we usually do it like this

Router router;
constructor (Router router) {
  this.router = router;
}

But in Angular, we don’t need the decleration outside the constructor, that is,

constructor (private router: Router) {}

After inject Router, we can now redirect page.
this.router.navigate(['welcome'])

Adding Route Parameter for Welcome Component
Requirement: we want to see Hello, user_name! in the Welcome page. How we get the user_name? We can pass it through URL, say our URL is like localhost:4200/welcome/teemo. Then how we do this?

  • First, in app-routing.module.ts, we set {path: 'welcome/:name'}, component: WelcomeComponent.
  • Activate Router in welcome.component.ts.
    constructor (private route: ActivatedRoute) {}
  • Get the name from the route.
    • this.route.snapshot: provides a snapshot of what the parameter is, which are passed in, and from there we can get list of params;
    • this.route.snapshot.params['name]': params is a Map and name is the key.
this.route.snapshot.params['name'];
  • Don’t forget to enhance the login router in login.component.ts.
this.router.navigate(['welcome', this.username])

Step 7: Creating ListTodos Component

7.1 How can we iterate an array ?

  • In java, we do it like for (Todo todo: todos) {}.
  • In Angular, we do it like *ngFor (let todo of todos). We can add it to HTML elements, like <tr *ngFor (let todo of todos), and todos is provided in .component.ts file.

7.2 Creating a link to Todos in Welcome Component
We can add a routerLink in <a> directly in welcome.component.html. That is,

You can manage your todos <a routerLink="/todos">here.</a>

Till now, we have the navigation from Login Page => Welcome Page => Todos Page.

7.3 How to format Date() ?
We use pipe, which is like,

<tr>{\{ todo.targetDate | date |uppercase }}</tr>

Angular Modules
Some of the angular modules are built into angular framework, such as FormsModule, AppRoutingModule, BrouserModule, NgModule.
Angular module is a group of components are that active which are dedicated for a specific purpose, and that module is the fundamental block of use in an angular app. If you want to use a component, you need to import the corresponding angular module.
Difference between angular module and javascript module?

  • angular module has the annotation in angular, and it is used to group angular componets, angular building blocks.
  • JavaScripte Module is any TypeScript or JavaScript file with code in it!
  • In comparison, angular module is something which has @NgModule, …, annotation on it. Javascript module is used to group different elements which are present in a single file, whereas an angular module is used to group different angular components. These components may be defined in different file.

Bootstrapping of Angular App with Root Module and Components
In the bootstrapping of an angular application, there are two things which play a crucial role. They are root Module and root component.

AppModule is the module which gets looked at first, app module would load the app component. When the app component is loaded in the end, HTML becauses of this app root the app.component.html is what is rendered.

Review of Angular Module and Component

  • Angular applications are built using a number of angular modules.
  • If you want to reuse a module, you need to import specific angular modules.
  • Whenever you create angular components, you need to associate it with an angular module. An angualr module contains multiple components.
  • Each component has a template which is basically a HTML file where typical HTML is combined with a few angular specific things, like angualr binding syntax. The style CSS part of it, becaue it is basically the place where put all the data in as well as how should we react to view actions.
  • Routing helps us navigate from one component to another.
  • ng directives and forms. *ngIf, pipes.

8.1 Adding Bootstrap

  • In style.css, we import bootstrp.
@import url(https://unpkg.com/bootstrap@4.1.0/dist/css/bootstrap.min.css)

8.2 Creating Menu and Footer
Create Menu and Footer components and add them in the app.component.html.

8.3 Using Bootstrap to create a menu with navigation links

Note that when using href the entire page is refreshed. If we don’t want to reload the entire page, we use routerLink. Since we are developing single page application, we use routerLink in the menu component here.

Step 10: Creating an Independent Authentication Service Component

10.1 Create an authentication service
ng generate service service/hardcodedAuthentication
Now we have created a service. If we want some to use some logic in the whole app among many components, we choose to use a service.
So what does a service do? It provides logic. If we want to use that logic, we use dependency injection.

Step 11: Using Session Storage to Store User Authentication Token

11.1 Using sessionStorage
sessionStorage is a Web API we can use directly.
sessionStorage.setItem('authenticaterUser', username);

  • You can only access data from Local/Session Storage that was set from your website!
  • Values set into Local Storage persist across browser restarts. Hence, it is less secure!

11.2 Enabling Menu Links based on user authentication token
<a *ngIf="this.hardcodedAuthentiationService.isUserLoggedIn()" routerLink="/todos" class="nav-link">Todos</a>
Note ngOnInit(){} is called only the first time that component is loaded.

11.3 Implementing Logout to remove User Authentication Token
sessionStorage.removeItem('authenticaterUser')

Step 12: Securing Components Using Routes Guard

12.1: Creating a RouteGuard service
ng generate service service/routeGuard

Let the RouteGuardService class implements CanActivate, which is from @angular/router. And override canActive method.

export class RouteGuardService implements CanActivate {

  constructor(private hardcodedAuthenticationService: HardcodedAuthenticationService,
              private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.hardcodedAuthenticationService.isUserLoggedIn())
      return true;
    
    //if user is not logged in navigate to login page
    this.router.navigate(['login']);

    return false;
  }

}

12.2 Using RouteGuard service

In app-routing.module.ts, we add it in the routes. That is,
{ path:'welcome/:name', component: WelcomeComponent, canActivate: [RouteGuardService] }

next_step

   Reprint policy


《TODO List Project Part I - Use Angular to build FrontEnd II》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC