Saturday 7 September 2019

Creating Angular app


Building Angular App

Agenda

What we are going to cover in this blog
1.     Generate our own component using ng generate component ‘name’ in Angular CLI
2.     Generating service using it to manipulate data
3.     How to include bootstrap in Angular app

Let’s get started –

Angular uses typescript as its default scripting language
First using npm generate component named ‘customer-forms’. If you don’t know what is npm or how to work with npm I recommend you click here
It will generate 4 files



One is page specific ‘customer-forms.component.css’ file other is ‘customer-forms.component.html’ next is ‘customer-forms.component.spec.ts’ which is a test file to test your code and last is ‘customer-forms.component.ts’ which is typescript file
Add this component to your ‘app.module.ts’ file
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule} from '@angular/forms'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomerFormsComponent } from './customer-forms/customer-forms.component';
import { CustomerViewComponent } from './customer-view/customer-view.component';

@NgModule({
  imports: [
    BrowserModule,
    CommonModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    // AppComponent,
    CustomerFormsComponent,
    CustomerViewComponent
  ],
  bootstrap: [
    // AppComponent,
    CustomerFormsComponent,
    CustomerViewComponent
  ]
})
export class AppModule { }


Now let’s create service.ts file for future use
Type ng generate service ‘name
export class CustomerFormsService{
    softwareData = [
        {Label:'None',Option:[{softwareId:0,SoftwareName:'None'}]},

        {Label:'ECommerce',Option:[
            {softwareId:1,SoftwareName:'Flipkart'},
            {softwareId:2,SoftwareName:'Amazon'}]
        },
   
        {Label:'Asset Manager',Option:[
            {softwareId:3,SoftwareName:'Asset Management'},
            {softwareId:4,SoftwareName:'Barcode Printer'},
            {softwareId:5,SoftwareName:'Asset Locator'}]
        },
   
        {Label:'School Management',Option:[
            {softwareId:6,SoftwareName:'Attendance Management'},
            {softwareId:7,SoftwareName:'Exam Management'},
            {softwareId:8,SoftwareName:'Faculty Management'},
            {softwareId:9,SoftwareName:'Schooling'}]
        },
   
        {Label:'Business',Option:[
            {softwareId:10,SoftwareName:'Warehouse'},
            {softwareId:11,SoftwareName:'Billing'},
            {softwareId:12,SoftwareName:'GST filing'}]
        }
    ];

    customerRequests = [
        {
        id: 1,
        CompanyName: 'Rohan IT',
        Name: 'Rohan Sharma',
        SoftwareId: 5,
        RelationshipDuration: 10
    },
    {
        id: 2,
        CompanyName: 'Infogain IT',
        Name: 'Lokesh Sharma',
        SoftwareId: 0,
        RelationshipDuration: 0
    },
    {
        id: 3,
        CompanyName: 'Infozech',
        Name: 'Rahul Kumar',
        SoftwareId: 9,
        RelationshipDuration: 11
    }];

    getAllSoftware()
    {
        return this.softwareData;
    }

    getSoftwareName(id:number)
    {
        return this.softwareData.find(x=> x.Option.find(y=> y.softwareId==id))
        .Option.find(z=> z.softwareId == id).SoftwareName;
    }

    get()
    {
        return this.customerRequests;
    }

    getOne(id: number)
    {
        return this.customerRequests.find( x=> x.id == id );
    }

    add(customerRequest)
    {
        console.log('In for add');
        this.customerRequests.push(customerRequest)
        console.log('Added sucessfully');
        console.log(this.customerRequests);
    }
   
    delete(customerRequest)
    {
        const index = this.customerRequests.indexOf(customerRequest);
        if(index == 0)
        {
            this.customerRequests.splice(index,1);
        }
    }
}

I have create ‘customer-forms.service.ts’ with data and some useful methods
We need to add this service to out ‘app.module.ts file as well. For that we shall add Providers properties in @NgModule directive and pass the service name there
import { CustomerFormsComponent } from './customer-forms/customer-forms.component';
import { CustomerFormsService } from '../Services/customer-forms.service';
import { CustomerViewComponent } from './customer-view/customer-view.component';

@NgModule({
  imports: [
    BrowserModule,
    CommonModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    // AppComponent,
    CustomerFormsComponent,
    CustomerViewComponent
  ],
  providers: [
    CustomerFormsService
  ],
  bootstrap: [
    // AppComponent,
    CustomerFormsComponent,
    CustomerViewComponent
  ]
})
export class AppModule { }

By doing this angular knows that this file will be injected in other classes or components.
Now lets make our component
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Validations } from '../Validations';
import { CustomerFormsService } from '../../Services/customer-forms.service';
import { CustomerViewComponent } from '../customer-view/customer-view.component';

@Component({
  selector: 'app-customer-forms',
  templateUrl: './customer-forms.component.html',
  styleUrls: ['./customer-forms.component.css']
})
export class CustomerFormsComponent implements OnInit {
  form: FormGroup;
  customerRequests;
  SoftwareData;
  constructor(private customerRequestService : CustomerFormsService) {
   
  }

  ngOnInit() {
    this.form = new FormGroup({
      CompanyName: new FormControl('', Validators.required),
      Name: new FormControl('', Validators.required),
      SoftwareId: new FormControl(''),
      RelationshipDuration: new FormControl('', Validators.compose([
        Validators.required
      ])),
    });
    this.SoftwareData = this.customerRequestService.getAllSoftware();
  }

  OnSubmit(CustomerRequest){
    console.log(CustomerRequest);
    this.customerRequestService.add(CustomerRequest);
    console.log('Added successfully');
  }

  SelectId(id)
  {
    debugger;
    this.form.value["SoftwareId"] = id.target.selectedOptions[0].value;
    console.log(this.form.value["SoftwareId"]);
    console.log(this.SoftwareData);
  }
}

Here passing values in constructor is dependency injection ‘private customerRequestService : CustomerFormsService
Angular is built upon very powerful dependency injection framework
i.e. ‘you can pass the dependency to the class itself’. Here the ‘customer-forms.component.ts’ needs the ‘customer-forms.service.ts’ which was injected to the component through constructor.
Use command npm install bootstrap to install bootstrap in your project and add the bootstrap to angular.json file
"styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.css"
            ],

In the ‘customer-forms.component.html’ write your html code
<header role="banner">
    <h1>Customer Request</h1>
    <nav role="navigation">
        <h2>Site navigation</h2>
    </nav>
</header>
<main role="main" class="container">
<section>
    <h3>Request</h3>
    <p>Existing customer should register their request like need of new deature in a software,
        fix to a bug in s/w, need special permission in a s/w or want a new s/w from scratch.
        We'll get in touch within 2 hours</p>
</section>
<section class="row">
    <form
    [formGroup]="form"
    (ngSubmit)="OnSubmit(form.value)" class="col-md-12">
    <p class="row">
        <label for="CompanyName" class="col-md-3 lable">Company Name</label>
        <input type="text" id="CompanyName" name="CompanyName" formControlName="CompanyName"
        class="col-md-8 form-control"/>
    </p>
    <p class="row">
        <label for="Name" class="col-md-3">Name</label>
        <input type="text" id="Name" name="Name" formControlName="Name"  class="col-md-8"/>
    </p>
    <p class="row">
        <label for="Softwares" class="col-md-3">Software Purchased</label>
        <select id="Softwares" name="Softwares" formControlName="SoftwareId" class="col-md-4"
        (change)="SelectId($event)">
            <optgroup *ngFor="let softwareGroup of SoftwareData" label="{{softwareGroup.Label}}">
                <option *ngFor="let softwareOption of softwareGroup.Option"
                [value]="softwareOption.softwareId">{{softwareOption.SoftwareName}}</option>
            </optgroup>
        </select>
    </p>
    <p class="row">
        <label for="RelationshipDuration" class="col-md-3"> Relationship with us</label>
        <input type="text " id="RelationshipDuration" maxlength="3" Min="18"
        name="RelationshipDuration" formControlName="RelationshipDuration" class="col-md-2"/>
        <span *ngIf="form.get('RelationshipDuration').hasError('required')" class="error col-md-6">
            Age must be  greater than 18 and cannot be blank!
        </span>
    </p>
    <p class="row">
        <input type="submit" value="Save" [disabled]="!form.valid" class="col-md-2 btn btn-success"/>
    </p>
    </form>
</section>
</main>
<footer></footer>


Now when you click on Save button you should see console window of your browser and see if the object is logged or not.

Thanks

No comments:

Post a Comment

Send All Azure App Insights Or Logs Data To Tool Like Datadog

  Introduction Microsoft Azure provides a variety of insights and monitoring logs that you can monitor to check the state of a resource and ...