Angular 10 – FormBuilder – Lead submission – Asp.Net Core API

//Angular 10 – FormBuilder – Lead submission – Asp.Net Core API

Angular 10 – FormBuilder – Lead submission – Asp.Net Core API

Source: https://www.youtube.com/watch?v=9WVG-tXl7XA

Source: https://coryrylan.com/blog/angular-form-builder-and-validation-management

Angular Structure that we will implement?
app{
  user{
    user.component.ts|.html|.css
    registration{
      registration.component.ts|.html|.css
    },
    shared{
      user.service.ts
    }
  },
  app.module.ts,
  app-routing.module.ts (route configs)
},
index.html

Angular 10 add BootStrap 4.0
npm install bootstrap@4.0 --save
add script on angular.json
"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts": ["node_modules/bootstrap/dist/js/bootstrap.js"]

How to add jQuery on index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>AngularWebapi</title>
    <base href="/" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
    <script
      src="https://code.jquery.com/jquery-3.5.1.min.js"
      integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
      crossorigin="anonymous"
    ></script>
  </head>
  <body>
    <app-root></app-root>
  </body>
</html>


How to add class into body tag?
add script on app.component.ts
import { Component, OnInit, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-root',
  //host: { class: 'text-center' }, this code add the class text-center into <app-root></app-root> tag
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  title = 'angular-webapi';

  /**
   *
   */
  constructor(private renderer: Renderer2) {}

  ngOnInit() {
    this.renderer.addClass(document.body, 'text-center'); //add class text-center on body tag
  }
}

How to create a component without CSS
ng g c user --inline-style

How to create a component without SPEC
ng g c user --spec=false //angular < 6
ng g c user --skipTests=true //angular > 9

How to create a component called Registration inner user folder without spec and css?
ng g c user/registration --skipTests=true --inline-style

How to create a user service without test-spec?
ng g s user --skipTests=true

How to create routes for the structure above?
add script on app.routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserComponent } from './user/user.component';
import { RegistrationComponent } from './user/registration/registration.component';

const routes: Routes = [
  {
    path: '',
    redirectTo: '/user/registration/',
    pathMatch: 'full',
  },
  {
    path: 'user',
    component: UserComponent,
    children: [
      {
        path: 'registration',
        component: RegistrationComponent, //user/registration
      },
    ],
  },
];

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

add script on app.component.html
<router-outlet></router-outlet>

add script on user/user.component.html
<div class="container">
  <div class="col-md-8 offset-md-2">
    <router-outlet></router-outlet>
  </div>
</div>

The script above will display the content of each route component.

How to create a registration form?

add script on registration.component.html
<div class="row mt-4">
  <div class="col-md-6">
    <div class="row" style="height: 450px">
      <img
        src="https://cdn0.iconfinder.com/data/icons/user-collection-4/512/add_user-512.png"
        class="mx-auto d-block"
      />
      <h1>User Registration</h1>
      <p>
        <em
          >-Using <strong>Asp.Net Core Web API</strong> and
          <strong> Angular 10</strong>
        </em>
      </p>
    </div>
  </div>
  <div class="col-md-6">
    <form
      [formGroup]="userService.formModel"
      autocomplete="off"
      (submit)="onSubmit()"
    >
      <div class="form-group required">
        <label>User Name</label>
        <input class="form-control" formControlName="UserName" />
        <label
          class="text-danger"
          *ngIf="
            userService.formModel.get('UserName').touched &&
            userService.formModel.get('UserName').errors?.required
          "
          >This field is mandatory</label
        >
      </div>
      <div class="form-group">
        <label>Email</label>
        <input class="form-control" formControlName="Email" />
        <label
          class="text-danger"
          *ngIf="
            userService.formModel.get('Email').touched &&
            userService.formModel.get('Email').errors?.email
          "
          >Invalid Email Address</label
        >
      </div>
      <div class="form-group">
        <label>Full Name</label>
        <input class="form-control" formControlName="FullName" />
      </div>
      <div formGroupName="Passwords">
        <div class="form-group required">
          <label>Password</label>
          <input
            type="password"
            class="form-control"
            formControlName="Password"
          />
          <label
            class="text-danger"
            *ngIf="
              userService.formModel.get('Passwords.Password').touched &&
              userService.formModel.get('Passwords.Password').errors?.required
            "
            >This field is Mandatory</label
          >
          <label
            class="text-danger"
            *ngIf="
              userService.formModel.get('Passwords.Password').touched &&
              userService.formModel.get('Passwords.Password').errors?.minlength
            "
            >Minimum 4 characters is required</label
          >
        </div>
        <div class="form-group required">
          <label>Confirm Password</label>
          <input
            type="password"
            class="form-control"
            formControlName="ConfirmPassword"
          />
          <label
            class="text-danger"
            *ngIf="
              userService.formModel.get('Passwords.ConfirmPassword').touched &&
              userService.formModel.get('Passwords.ConfirmPassword').errors
                ?.required
            "
            >This field is Mandatory</label
          >
          <label
            class="text-danger"
            *ngIf="
              userService.formModel.get('Passwords.ConfirmPassword').touched &&
              userService.formModel.get('Passwords.ConfirmPassword').errors
                ?.passwordMismatch
            "
            >Mismatch Password</label
          >
        </div>
      </div>
      <div class="form-row">
        <div class="form-group col-md-8 offset-md-2">
          <button
            type="submit"
            class="btn btn-lg btn-block"
            [disabled]="!userService.formModel.valid"
          >
            Sign Up
          </button>
        </div>
      </div>
    </form>
  </div>
</div>

add script on shared/user.service.ts
import { Injectable } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  BaseURI: string = 'http://localhost:55460';

  constructor(private fb: FormBuilder, private http: HttpClient) {}

  formModel = this.fb.group({
    UserName: ['', Validators.required],
    FullName: [''],
    Email: ['', Validators.email],
    Passwords: this.fb.group(
      {
        Password: ['', [Validators.required, Validators.minLength(4)]],
        ConfirmPassword: ['', Validators.required],
      },
      { validator: this.comparePasswords }
    ),
  });

  comparePasswords(fb: FormGroup) {
    let confirmPswrdCtrl = fb.get('ConfirmPassword');
    //password mismatch
    if (
      confirmPswrdCtrl.errors == null ||
      'passwordMismatch' in confirmPswrdCtrl.errors
    ) {
      if (fb.get('Password').value != confirmPswrdCtrl.value) {
        confirmPswrdCtrl.setErrors({ passwordMismatch: true });
      } else {
        confirmPswrdCtrl.setErrors(null);
      }
    }
  }

  register() {
    var body = {
      UserName: this.formModel.value.UserName,
      Email: this.formModel.value.Email,
      FullName: this.formModel.value.FullName,
      Password: this.formModel.value.Passwords.Password,
    };

    return this.http.post(this.BaseURI + '/api/ApplicationUser/Register', body);
  }
}

add script on registration.component.ts
import { UserService } from './../../shared/user.service';
import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styles: [],
})
export class RegistrationComponent implements OnInit {
  constructor(public userService: UserService, private toastr: ToastrService) {}

  ngOnInit(): void {
    this.userService.formModel.reset();
  }

  onSubmit() {
    this.userService.register().subscribe(
      (res: any) => {
        if (res.succeeded) {
          this.userService.formModel.reset();
          this.toastr.success('New User created', 'Registration successful.');
        } else {
          res.errors.forEach((element) => {
            switch (element.code) {
              case 'DuplicateUserName':
                //Username is already taken
                this.toastr.error(
                  'Username is already taken',
                  'Registration Failed'
                );
                break;
              default:
                //registration failed
                this.toastr.error(element.description, 'Registration Failed');
                break;
            }
          });
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }
}

add script on app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
import { UserComponent } from './user/user.component';
import { RegistrationComponent } from './user/registration/registration.component';
import { UserService } from './shared/user.service';

@NgModule({
  declarations: [AppComponent, UserComponent, RegistrationComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot({
      progressBar: true,
    }),
  ],
  providers: [UserService],
  bootstrap: [AppComponent],
})
export class AppModule {}

add script on angular.json
"styles": [
  "src/styles.css",
  "node_modules/ngx-toastr/toastr.css", //this one
  "node_modules/bootstrap/dist/css/bootstrap.css"
],

add script on styles.css
/* You can add global styles to this file, and also import other style files */

@import "https://getbootstrap.com/docs/4.0/examples/cover/cover.css";

div.form-group.required > label:first-child:after {
  content: "*";
  color: red;
  padding-left: 5px;
}
By |2020-08-27T16:26:07-06:00August 27th, 2020|Web Developer|Comments Off on Angular 10 – FormBuilder – Lead submission – Asp.Net Core API

About the Author: