Angular Course with Tailwind CSS – Lesson 4: User registration

For almost three weeks, we are creating an Angular 9 fintech application together, step by step with this Angular Course.

We’ve already gone through the setting the project and creating a login form template, then we’ve created the logic for our login form, and last week we displayed user data in the template.

Today, it’s time for lesson 4, where we will handle user registration.

If you didn’t start with me, feel free to go through all the lessons until now. Or you can get the code from the previous lesson and jump straight to this lesson. Here’s a link to our Github repository for this Angular Course.

Code for lesson 3

There’s also one more thing you should know. We are building a backend course along with this frontend Angular Course, so you may use them both to create a fully working app. Here’s the link to the backend Golang Course.

In the meantime, we are also creating a Node.js Course, but it’s still a few steps behind.

And of course, as always, here’s the video version of this lesson.

So, open the code in your favorite code editor, run your backend, and let's start with user registration in Angular 9.

1. Create a new component

Let's start by creating our registration form. In the beginning, we'll use Angular CLI to generate the register component.
$ ng generate component register
When it's ready, we need to visit Tailwind CSS and get the form code!

2. Building registration form template

We are going to build a form that is similar to our login form, it'll be almost the same, just we need a few more fields, like email and confirm password.

Let’s open the register.component.html file, and let’s create the following code.

<div id="register-container" class="flex container mx-auto items-center justify-center">
  <div class="w-full max-w-xs">
    <form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
      <img src="../../assets/logo.png" class="logo" />
      <div class="mb-4">
        <label class="block text-gray-700 text-sm font-bold mb-2" for="username">
          Username
        </label>
        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="username" type="text" placeholder="Username">
      </div>
      <div class="mb-4">
        <label class="block text-gray-700 text-sm font-bold mb-2" for="email">
          Email
        </label>
        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="email" type="email" placeholder="Email">
      </div>
      <div class="mb-4">
        <label class="block text-gray-700 text-sm font-bold mb-2" for="password">
          Password
        </label>
        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="password" type="password" placeholder="******************">
      </div>
      <div class="mb-4">
        <label class="block text-gray-700 text-sm font-bold mb-2" for="confirm-password">
          Confirm Password
        </label>
        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline" id="confirm-password" type="password" placeholder="******************">
      </div>
      <div class="flex items-center justify-between">
        <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button">
          Sign In
        </button>
      </div>
      <div class="flex items-center justify-between mt-4">
        <p class="inline-block align-baseline text-sm text-blue-500">Already have an account? 
          <a class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800">
            Sign in
          </a>
        </p>
      </div>
    </form>
    <p class="text-center text-gray-500 text-xs">
      &copy;2020 Banking App by Duomly. All rights reserved.
    </p>
  </div>
</div>
Okay, now let's open the register.component.scss file and place there the following styling.
#register-container {
  min-height: 100vh;
  min-width: 100vw;
  color: white;
  position: relative;
  background-image: url('../../assets/background.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  .logo {
    max-height: 60px;
    margin: auto;
    margin-bottom: 30px;
  }
  .notification {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
  }
}
Great, when this step is completed, it's time for setting the route for our component and make it visible.

3. Setting the route

To set up the route for our new component, let's open the app-routing.module.ts file and we need to import our newly created component.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuardGuard } from './services/guards/auth-guard.guard';

import { LoginComponent } from ‘./login/login.component’;
import { DashboardComponent } from ‘./dashboard/dashboard.component’;
import { RegisterComponent } from ‘./register/register.component’;

const routes: Routes = [
{ path: ‘’, component: LoginComponent },
{ path: ‘register’, component: RegisterComponent },
{ path: ‘dashboard’, component: DashboardComponent, canActivate: [AuthGuardGuard] }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }


When your Routes look like in the code above, we will add links in the LoginComponent and RegisterComponent. Let’s start from the register.component.html file, where we are going to send user to the login form if he or she already has the account.

<div class="flex items-center justify-between mt-4">
  <p class="inline-block align-baseline text-sm text-blue-500">Already have an account? 
    <a class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800" [routerLink]="['/']">
      Sign in
    </a>
  </p>
</div>

Now, we will do a similar thing, but we will add a link that will allow users to go to the registration form to set up the account. Let’s open the login.component.html file, and let’s do small refactoring.

<div class="flex items-center justify-between mt-4">
  <p class="inline-block align-baseline text-sm text-blue-500">Don't have an account? 
    <a class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800" [routerLink]="['/register']">
      Sign up
    </a>
  </p>
</div>

Great, now your login and register forms should look like below.Angular Course by Duomly - User registration

Now, we will start creating the logic for our registration feature.

4. Handling inputs

It's time to create the function which will save the input values from our registration form. Open the registe.component.ts file, and let's start with defining the following values.
export class RegisterComponent implements OnInit {
  username = '';
  email = '';
  password = '';
  confirmPassword = '';

constructor() { }

ngOnInit(): void {}

onKey(event: any, type: string) {
if (type === ‘username’) {
this.username = event.target.value;
} else if (type === ‘email’) {
this.email = event.target.value;
} else if (type === ‘password’) {
this.password = event.target.value;
} else if (type === ‘confirmPassword’) {
this.confirmPassword = event.target.value;
}
}
}


Now, we can add this function to our template. Let’s go back to the register.component.html and add the function to each input.

<form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
     <img src="../../assets/logo.png" class="logo" />
     <div class="mb-4">
       <label class="block text-gray-700 text-sm font-bold mb-2" for="username">
         Username
       </label>
       <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="username" type="text" placeholder="Username" (keyup)="onKey($event, 'username')">
     </div>
     <div class="mb-4">
       <label class="block text-gray-700 text-sm font-bold mb-2" for="email">
         Email
       </label>
       <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="email" type="email" placeholder="Email" (keyup)="onKey($event, 'email')">
     </div>
     <div class="mb-4">
       <label class="block text-gray-700 text-sm font-bold mb-2" for="password">
         Password
       </label>
       <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="password" type="password" placeholder="******************" (keyup)="onKey($event, 'password')">
     </div>
     <div class="mb-4">
       <label class="block text-gray-700 text-sm font-bold mb-2" for="confirm-password">
         Confirm Password
       </label>
       <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline" id="confirm-password" type="password" placeholder="******************" (keyup)="onKey($event, 'confirmPassword')">
     </div>
     <div class="flex items-center justify-between">
       <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button">
         Sign In
       </button>
     </div>
     <div class="flex items-center justify-between mt-4">
       <p class="inline-block align-baseline text-sm text-blue-500">Already have an account? 
         <a class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800" [routerLink]="['/']">
           Sign in
         </a>
       </p>
     </div>
   </form>
Our form is updated right now, so we can perform the validation of our inputs.

5. Validation

Before we send the API call to our backend, we have to make sure the values that are passed in the form are in the right format and are saved for our application. Because if you remember the SQL injection lesson by my friend, it can be dangerous to our application to send anything to the backend without the check.

Let’s open the register.component.ts file, and let’s create the following code.

export class RegisterComponent implements OnInit {
  username = '';
  email = '';
  password = '';
  confirmPassword = '';
  valid = {
    username: true,
    email: true,
    password: true,
  };

  constructor() { }

  ngOnInit(): void {}

  validate(type: string): void {
    const usernamePattern = /^[\w-.]*$/;
    const emailPattern = /\S+@\S+\.\S+/;

    if (type === 'username') {
      if (this.username.length < 5) {
        this.valid.username = false;
      } else {
        this.valid.username = usernamePattern.test(this.username);
      }
    } else if (type === 'email') {
      this.valid.email = emailPattern.test(this.email);
    } else if (type === ('confirmPassword' || 'password')) {
      if (this.password !== this.confirmPassword) {
        this.valid.password = false;
      } else {
        this.valid.password = true;
      }
    }
  }

  onKey(event: any, type: string) {
    if (type === 'username') {
      this.username = event.target.value;
    } else if (type === 'email') {
      this.email = event.target.value;
    } else if (type === 'password') {
      this.password = event.target.value;
    } else if (type === 'confirmPassword') {
      this.confirmPassword = event.target.value;
    }
    this.validate(type);
  }
}

To make our validation complete, we have to let users know which fields have errors and to do it, we will display error messages conditionally. Let’s jump into the register.component.html file and make sure your code looks like this.

<form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
  <img src="../../assets/logo.png" class="logo" />
  <div class="mb-4">
    <label class="block text-gray-700 text-sm font-bold mb-2" for="username">
      Username
    </label>
    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="username" type="text" placeholder="Username" (keyup)="onKey($event, 'username')">
    <p *ngIf="!valid.username" class="text-red-500 text-xs italic">Username can consist of letters and numbers only and the minimum length is 5!</p>
  </div>
  <div class="mb-4">
    <label class="block text-gray-700 text-sm font-bold mb-2" for="email">
      Email
    </label>
    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="email" type="email" placeholder="Email" (keyup)="onKey($event, 'email')">
    <p *ngIf="!valid.email" class="text-red-500 text-xs italic">Your email is not correct!</p>
  </div>
  <div class="mb-4">
    <label class="block text-gray-700 text-sm font-bold mb-2" for="password">
      Password
    </label>
    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="password" type="password" placeholder="******************" (keyup)="onKey($event, 'password')">
  </div>
  <div class="mb-4">
    <label class="block text-gray-700 text-sm font-bold mb-2" for="confirm-password">
      Confirm Password
    </label>
    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline" id="confirm-password" type="password" placeholder="******************" (keyup)="onKey($event, 'confirmPassword')">
    <p *ngIf="!valid.password" class="text-red-500 text-xs italic">Passwords are different!</p>
  </div>
  <div class="flex items-center justify-between">
    <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button">
      Sign In
    </button>
  </div>
  <div class="flex items-center justify-between mt-4">
    <p class="inline-block align-baseline text-sm text-blue-500">Already have an account? 
      <a class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800" [routerLink]="['/']">
        Sign in
      </a>
    </p>
  </div>
</form>
Great, when this part is done, we need to do some refactoring, as our app is growing and we would like to keep is smart, and comfortable.

6. Refactoring

The thing we will change now is our Login Service. We would like to handle all functions which apply to the user in one service, that's why I'd like to rename it to UserService. You can do it manually or use any dedicated plugging for your code editor. Remember to check all the imports when it's done.

The other thing which we need to change is our proxy.conf.json file.

Let’s open it and change your code to the one here.

{
  "/api/*": {
    "target": "http://localhost:8888",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    }
  }
}
When you finished this, please re-run your application with ng serve.

7. register() function

We can start building the register function in the UserService. Let's open the newly refactored user.service.ts file, and let's start by changing the URL value.
export class UserService {
  url: any = 'http://localhost:4200/api/';
  ...
}
We need to make a change in our login() function, as we've changed the URL to make it reusable.
login(Username: string, Password: string): any {
    this.http.post(`${this.url}login`, { Username, Password }, httpOptions).toPromise().then((res: any) => {
       ...
    })
}
And finally, we can create our register() function, which will be very similar to the login() functions.
register(Username: string, Email: string, Password: string): any {
  this.http.post(`${this.url}register`, { Username, Email, Password }).toPromise().then((res: any) => {
    if (res && res.jwt) {
      sessionStorage.setItem('jwt', res.jwt);
      this.errorSubject.next(null);
      if (res.data) {
        this.userSubject.next(res.data);
      }
      this.router.navigateByUrl('dashboard');
    } else if (res.Message) {
      this.errorSubject.next(res.Message);
    }
  });
}
Great! It's time to implement our API call in the register.component.ts file. Also, let's implement listening for the error in the ngOnInit() method.
export class RegisterComponent implements OnInit {
  error = null;

ngOnInit(): void {
this.userService
.errorSubject
.subscribe(errorMessage => {
this.error = errorMessage;
});
}

onRegister(): void {
if (this.valid.username && this.valid.email && this.valid.password) {
this.userService
.register(this.username, this.email, this.password);
}
}
}


Perfect, let’s add the onRegister() function to our register.component.html template.

<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button" (click)="onRegister()">
  Sign In
</button>

Great, it’s time for the last step, which is adding the error notification to the template.

8. Error notification

In our register.component.html file, we are going to add the notification like in the Login Form, which will be shown if there is an error returned.
<div *ngIf="error" class="notification bg-indigo-900 text-center py-4 lg:px-4">
  <div class="p-2 bg-indigo-800 items-center text-indigo-100 leading-none lg:rounded-full flex lg:inline-flex" role="alert">
    <span class="flex rounded-full bg-indigo-500 uppercase px-2 py-1 text-xs font-bold mr-3">ERROR</span>
    <span class="font-semibold mr-2 text-left flex-auto">{{error}}</span>
  </div>
</div>
And voila! The registration is ready, and you can test it! Remember to have the backend running.

Conclusion

If you didn't manage to get the code correctly and have any issues remember that you can check out the code for this lesson at our Github repository.

Angular Course - Lesson 4 - Code

Also, remember to stay updated with our backend courses, Golang Course and Node.js Course, where the new features are appearing every week, so we can continue implementing them on the frontend.

In the next lessons, we will be asking for user data from backend and creating the money transfers.

Stay tuned and let us know in the comments what else you’d like to build!

Thank you for reading,
Anna from Duomly

#web-development #angular #typescript #html #css

What is GEEK

Buddha Community

Angular Course with Tailwind CSS – Lesson 4: User registration

Angular Course with Tailwind CSS – Lesson 4: User registration

For almost three weeks, we are creating an Angular 9 fintech application together, step by step with this Angular Course.

We’ve already gone through the setting the project and creating a login form template, then we’ve created the logic for our login form, and last week we displayed user data in the template.

Today, it’s time for lesson 4, where we will handle user registration.

If you didn’t start with me, feel free to go through all the lessons until now. Or you can get the code from the previous lesson and jump straight to this lesson. Here’s a link to our Github repository for this Angular Course.

Code for lesson 3

There’s also one more thing you should know. We are building a backend course along with this frontend Angular Course, so you may use them both to create a fully working app. Here’s the link to the backend Golang Course.

In the meantime, we are also creating a Node.js Course, but it’s still a few steps behind.

And of course, as always, here’s the video version of this lesson.

So, open the code in your favorite code editor, run your backend, and let's start with user registration in Angular 9.

1. Create a new component

Let's start by creating our registration form. In the beginning, we'll use Angular CLI to generate the register component.
$ ng generate component register
When it's ready, we need to visit Tailwind CSS and get the form code!

2. Building registration form template

We are going to build a form that is similar to our login form, it'll be almost the same, just we need a few more fields, like email and confirm password.

Let’s open the register.component.html file, and let’s create the following code.

<div id="register-container" class="flex container mx-auto items-center justify-center">
  <div class="w-full max-w-xs">
    <form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
      <img src="../../assets/logo.png" class="logo" />
      <div class="mb-4">
        <label class="block text-gray-700 text-sm font-bold mb-2" for="username">
          Username
        </label>
        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="username" type="text" placeholder="Username">
      </div>
      <div class="mb-4">
        <label class="block text-gray-700 text-sm font-bold mb-2" for="email">
          Email
        </label>
        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="email" type="email" placeholder="Email">
      </div>
      <div class="mb-4">
        <label class="block text-gray-700 text-sm font-bold mb-2" for="password">
          Password
        </label>
        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="password" type="password" placeholder="******************">
      </div>
      <div class="mb-4">
        <label class="block text-gray-700 text-sm font-bold mb-2" for="confirm-password">
          Confirm Password
        </label>
        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline" id="confirm-password" type="password" placeholder="******************">
      </div>
      <div class="flex items-center justify-between">
        <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button">
          Sign In
        </button>
      </div>
      <div class="flex items-center justify-between mt-4">
        <p class="inline-block align-baseline text-sm text-blue-500">Already have an account? 
          <a class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800">
            Sign in
          </a>
        </p>
      </div>
    </form>
    <p class="text-center text-gray-500 text-xs">
      &copy;2020 Banking App by Duomly. All rights reserved.
    </p>
  </div>
</div>
Okay, now let's open the register.component.scss file and place there the following styling.
#register-container {
  min-height: 100vh;
  min-width: 100vw;
  color: white;
  position: relative;
  background-image: url('../../assets/background.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  .logo {
    max-height: 60px;
    margin: auto;
    margin-bottom: 30px;
  }
  .notification {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
  }
}
Great, when this step is completed, it's time for setting the route for our component and make it visible.

3. Setting the route

To set up the route for our new component, let's open the app-routing.module.ts file and we need to import our newly created component.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuardGuard } from './services/guards/auth-guard.guard';

import { LoginComponent } from ‘./login/login.component’;
import { DashboardComponent } from ‘./dashboard/dashboard.component’;
import { RegisterComponent } from ‘./register/register.component’;

const routes: Routes = [
{ path: ‘’, component: LoginComponent },
{ path: ‘register’, component: RegisterComponent },
{ path: ‘dashboard’, component: DashboardComponent, canActivate: [AuthGuardGuard] }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }


When your Routes look like in the code above, we will add links in the LoginComponent and RegisterComponent. Let’s start from the register.component.html file, where we are going to send user to the login form if he or she already has the account.

<div class="flex items-center justify-between mt-4">
  <p class="inline-block align-baseline text-sm text-blue-500">Already have an account? 
    <a class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800" [routerLink]="['/']">
      Sign in
    </a>
  </p>
</div>

Now, we will do a similar thing, but we will add a link that will allow users to go to the registration form to set up the account. Let’s open the login.component.html file, and let’s do small refactoring.

<div class="flex items-center justify-between mt-4">
  <p class="inline-block align-baseline text-sm text-blue-500">Don't have an account? 
    <a class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800" [routerLink]="['/register']">
      Sign up
    </a>
  </p>
</div>

Great, now your login and register forms should look like below.Angular Course by Duomly - User registration

Now, we will start creating the logic for our registration feature.

4. Handling inputs

It's time to create the function which will save the input values from our registration form. Open the registe.component.ts file, and let's start with defining the following values.
export class RegisterComponent implements OnInit {
  username = '';
  email = '';
  password = '';
  confirmPassword = '';

constructor() { }

ngOnInit(): void {}

onKey(event: any, type: string) {
if (type === ‘username’) {
this.username = event.target.value;
} else if (type === ‘email’) {
this.email = event.target.value;
} else if (type === ‘password’) {
this.password = event.target.value;
} else if (type === ‘confirmPassword’) {
this.confirmPassword = event.target.value;
}
}
}


Now, we can add this function to our template. Let’s go back to the register.component.html and add the function to each input.

<form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
     <img src="../../assets/logo.png" class="logo" />
     <div class="mb-4">
       <label class="block text-gray-700 text-sm font-bold mb-2" for="username">
         Username
       </label>
       <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="username" type="text" placeholder="Username" (keyup)="onKey($event, 'username')">
     </div>
     <div class="mb-4">
       <label class="block text-gray-700 text-sm font-bold mb-2" for="email">
         Email
       </label>
       <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="email" type="email" placeholder="Email" (keyup)="onKey($event, 'email')">
     </div>
     <div class="mb-4">
       <label class="block text-gray-700 text-sm font-bold mb-2" for="password">
         Password
       </label>
       <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="password" type="password" placeholder="******************" (keyup)="onKey($event, 'password')">
     </div>
     <div class="mb-4">
       <label class="block text-gray-700 text-sm font-bold mb-2" for="confirm-password">
         Confirm Password
       </label>
       <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline" id="confirm-password" type="password" placeholder="******************" (keyup)="onKey($event, 'confirmPassword')">
     </div>
     <div class="flex items-center justify-between">
       <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button">
         Sign In
       </button>
     </div>
     <div class="flex items-center justify-between mt-4">
       <p class="inline-block align-baseline text-sm text-blue-500">Already have an account? 
         <a class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800" [routerLink]="['/']">
           Sign in
         </a>
       </p>
     </div>
   </form>
Our form is updated right now, so we can perform the validation of our inputs.

5. Validation

Before we send the API call to our backend, we have to make sure the values that are passed in the form are in the right format and are saved for our application. Because if you remember the SQL injection lesson by my friend, it can be dangerous to our application to send anything to the backend without the check.

Let’s open the register.component.ts file, and let’s create the following code.

export class RegisterComponent implements OnInit {
  username = '';
  email = '';
  password = '';
  confirmPassword = '';
  valid = {
    username: true,
    email: true,
    password: true,
  };

  constructor() { }

  ngOnInit(): void {}

  validate(type: string): void {
    const usernamePattern = /^[\w-.]*$/;
    const emailPattern = /\S+@\S+\.\S+/;

    if (type === 'username') {
      if (this.username.length < 5) {
        this.valid.username = false;
      } else {
        this.valid.username = usernamePattern.test(this.username);
      }
    } else if (type === 'email') {
      this.valid.email = emailPattern.test(this.email);
    } else if (type === ('confirmPassword' || 'password')) {
      if (this.password !== this.confirmPassword) {
        this.valid.password = false;
      } else {
        this.valid.password = true;
      }
    }
  }

  onKey(event: any, type: string) {
    if (type === 'username') {
      this.username = event.target.value;
    } else if (type === 'email') {
      this.email = event.target.value;
    } else if (type === 'password') {
      this.password = event.target.value;
    } else if (type === 'confirmPassword') {
      this.confirmPassword = event.target.value;
    }
    this.validate(type);
  }
}

To make our validation complete, we have to let users know which fields have errors and to do it, we will display error messages conditionally. Let’s jump into the register.component.html file and make sure your code looks like this.

<form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
  <img src="../../assets/logo.png" class="logo" />
  <div class="mb-4">
    <label class="block text-gray-700 text-sm font-bold mb-2" for="username">
      Username
    </label>
    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="username" type="text" placeholder="Username" (keyup)="onKey($event, 'username')">
    <p *ngIf="!valid.username" class="text-red-500 text-xs italic">Username can consist of letters and numbers only and the minimum length is 5!</p>
  </div>
  <div class="mb-4">
    <label class="block text-gray-700 text-sm font-bold mb-2" for="email">
      Email
    </label>
    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="email" type="email" placeholder="Email" (keyup)="onKey($event, 'email')">
    <p *ngIf="!valid.email" class="text-red-500 text-xs italic">Your email is not correct!</p>
  </div>
  <div class="mb-4">
    <label class="block text-gray-700 text-sm font-bold mb-2" for="password">
      Password
    </label>
    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="password" type="password" placeholder="******************" (keyup)="onKey($event, 'password')">
  </div>
  <div class="mb-4">
    <label class="block text-gray-700 text-sm font-bold mb-2" for="confirm-password">
      Confirm Password
    </label>
    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline" id="confirm-password" type="password" placeholder="******************" (keyup)="onKey($event, 'confirmPassword')">
    <p *ngIf="!valid.password" class="text-red-500 text-xs italic">Passwords are different!</p>
  </div>
  <div class="flex items-center justify-between">
    <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button">
      Sign In
    </button>
  </div>
  <div class="flex items-center justify-between mt-4">
    <p class="inline-block align-baseline text-sm text-blue-500">Already have an account? 
      <a class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800" [routerLink]="['/']">
        Sign in
      </a>
    </p>
  </div>
</form>
Great, when this part is done, we need to do some refactoring, as our app is growing and we would like to keep is smart, and comfortable.

6. Refactoring

The thing we will change now is our Login Service. We would like to handle all functions which apply to the user in one service, that's why I'd like to rename it to UserService. You can do it manually or use any dedicated plugging for your code editor. Remember to check all the imports when it's done.

The other thing which we need to change is our proxy.conf.json file.

Let’s open it and change your code to the one here.

{
  "/api/*": {
    "target": "http://localhost:8888",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    }
  }
}
When you finished this, please re-run your application with ng serve.

7. register() function

We can start building the register function in the UserService. Let's open the newly refactored user.service.ts file, and let's start by changing the URL value.
export class UserService {
  url: any = 'http://localhost:4200/api/';
  ...
}
We need to make a change in our login() function, as we've changed the URL to make it reusable.
login(Username: string, Password: string): any {
    this.http.post(`${this.url}login`, { Username, Password }, httpOptions).toPromise().then((res: any) => {
       ...
    })
}
And finally, we can create our register() function, which will be very similar to the login() functions.
register(Username: string, Email: string, Password: string): any {
  this.http.post(`${this.url}register`, { Username, Email, Password }).toPromise().then((res: any) => {
    if (res && res.jwt) {
      sessionStorage.setItem('jwt', res.jwt);
      this.errorSubject.next(null);
      if (res.data) {
        this.userSubject.next(res.data);
      }
      this.router.navigateByUrl('dashboard');
    } else if (res.Message) {
      this.errorSubject.next(res.Message);
    }
  });
}
Great! It's time to implement our API call in the register.component.ts file. Also, let's implement listening for the error in the ngOnInit() method.
export class RegisterComponent implements OnInit {
  error = null;

ngOnInit(): void {
this.userService
.errorSubject
.subscribe(errorMessage => {
this.error = errorMessage;
});
}

onRegister(): void {
if (this.valid.username && this.valid.email && this.valid.password) {
this.userService
.register(this.username, this.email, this.password);
}
}
}


Perfect, let’s add the onRegister() function to our register.component.html template.

<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button" (click)="onRegister()">
  Sign In
</button>

Great, it’s time for the last step, which is adding the error notification to the template.

8. Error notification

In our register.component.html file, we are going to add the notification like in the Login Form, which will be shown if there is an error returned.
<div *ngIf="error" class="notification bg-indigo-900 text-center py-4 lg:px-4">
  <div class="p-2 bg-indigo-800 items-center text-indigo-100 leading-none lg:rounded-full flex lg:inline-flex" role="alert">
    <span class="flex rounded-full bg-indigo-500 uppercase px-2 py-1 text-xs font-bold mr-3">ERROR</span>
    <span class="font-semibold mr-2 text-left flex-auto">{{error}}</span>
  </div>
</div>
And voila! The registration is ready, and you can test it! Remember to have the backend running.

Conclusion

If you didn't manage to get the code correctly and have any issues remember that you can check out the code for this lesson at our Github repository.

Angular Course - Lesson 4 - Code

Also, remember to stay updated with our backend courses, Golang Course and Node.js Course, where the new features are appearing every week, so we can continue implementing them on the frontend.

In the next lessons, we will be asking for user data from backend and creating the money transfers.

Stay tuned and let us know in the comments what else you’d like to build!

Thank you for reading,
Anna from Duomly

#web-development #angular #typescript #html #css

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Roberta  Ward

Roberta Ward

1593184320

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.

Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.

We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.

What is a Component in Angular?

Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})

Role of App Module

Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.

@NgModule({
declarations: [
  AppComponent,
],
imports: [
  BrowserModule,
  HttpClientModule,
  AppRoutingModule,
  FormsModule
],
bootstrap: [AppComponent]
})

What is Data Binding?

Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular

Roberta  Ward

Roberta Ward

1595344320

Wondering how to upgrade your skills in the pandemic? Here's a simple way you can do it.

Corona Virus Pandemic has brought the world to a standstill.

Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public places are shut down, the country’s economy is suffering, human health is on stake, people are losing their jobs and nobody knows how worse it can get.

Since most of the places are on lockdown, and you are working from home or have enough time to nourish your skills, then you should use this time wisely! We always complain that we want some ‘time’ to learn and upgrade our knowledge but don’t get it due to our ‘busy schedules’. So, now is the time to make a ‘list of skills’ and learn and upgrade your skills at home!

And for the technology-loving people like us, Knoldus Techhub has already helped us a lot in doing it in a short span of time!

If you are still not aware of it, don’t worry as Georgia Byng has well said,

“No time is better than the present”

– Georgia Byng, a British children’s writer, illustrator, actress and film producer.

No matter if you are a developer (be it front-end or back-end) or a data scientisttester, or a DevOps person, or, a learner who has a keen interest in technology, Knoldus Techhub has brought it all for you under one common roof.

From technologies like Scala, spark, elastic-search to angular, go, machine learning, it has a total of 20 technologies with some recently added ones i.e. DAML, test automation, snowflake, and ionic.

How to upgrade your skills?

Every technology in Tech-hub has n number of templates. Once you click on any specific technology you’ll be able to see all the templates of that technology. Since these templates are downloadable, you need to provide your email to get the template downloadable link in your mail.

These templates helps you learn the practical implementation of a topic with so much of ease. Using these templates you can learn and kick-start your development in no time.

Apart from your learning, there are some out of the box templates, that can help provide the solution to your business problem that has all the basic dependencies/ implementations already plugged in. Tech hub names these templates as xlr8rs (pronounced as accelerators).

xlr8rs make your development real fast by just adding your core business logic to the template.

If you are looking for a template that’s not available, you can also request a template may be for learning or requesting for a solution to your business problem and tech-hub will connect with you to provide you the solution. Isn’t this helpful 🙂

Confused with which technology to start with?

To keep you updated, the Knoldus tech hub provides you with the information on the most trending technology and the most downloaded templates at present. This you’ll be informed and learn the one that’s most trending.

Since we believe:

“There’s always a scope of improvement“

If you still feel like it isn’t helping you in learning and development, you can provide your feedback in the feedback section in the bottom right corner of the website.

#ai #akka #akka-http #akka-streams #amazon ec2 #angular 6 #angular 9 #angular material #apache flink #apache kafka #apache spark #api testing #artificial intelligence #aws #aws services #big data and fast data #blockchain #css #daml #devops #elasticsearch #flink #functional programming #future #grpc #html #hybrid application development #ionic framework #java #java11 #kubernetes #lagom #microservices #ml # ai and data engineering #mlflow #mlops #mobile development #mongodb #non-blocking #nosql #play #play 2.4.x #play framework #python #react #reactive application #reactive architecture #reactive programming #rust #scala #scalatest #slick #software #spark #spring boot #sql #streaming #tech blogs #testing #user interface (ui) #web #web application #web designing #angular #coronavirus #daml #development #devops #elasticsearch #golang #ionic #java #kafka #knoldus #lagom #learn #machine learning #ml #pandemic #play framework #scala #skills #snowflake #spark streaming #techhub #technology #test automation #time management #upgrade

Clara  Gutmann

Clara Gutmann

1599459851

Angular Sass: How To Use Sass In Angular 9 Tutorial

Angular supports Sass, CSS, and Less to style global application styles as well as component styles. Angular components styles have an effective CSS encapsulation mechanism that assures any component CSS is local to the component and does not globally alter any styles.

Angular Sass Example

Why use Angular Sass? Well!! Sass (Syntactically Awesome Style Sheets) is an extension of CSS that allows you to use things like variables, nested rules, inline imports, and more. It also supports you to keep things organized and enables you to create style sheets faster.

In short,  Sass is a CSS preprocessor, which combines unique features such as variables, nested rules, and mixins (sometimes referred to as syntactic sugar) into regular CSS. The main object of Sass is to make the CSS coding process more comfortable and more efficient.

Sass is compatible with all versions of CSS. When working with the Angular CLI, the default stylesheets have the .css extension. We are using Angular CLI 8. So, if you have not used previously, then please upgrade your  CLI version. We will use the Bootstrap 4 Framework for this demo and see how we can configure the Sass in our Angular 9 application.

#angular #angular 9 #angular cli #css #angular sass