Creating your first Angular App

 Agenda
 
Given below is the list of content that we are going to cover in this blog.
  1. Generating our own component using ng generate component ‘name’ in Angular CLI.
  2. Generating a service and using it to manipulate the data.
  3. Including bootstrap in our Angular app
Let’s get started.
 
Angular uses TypeScript as its default scripting language.
 
First, using the npm, let us generate a component named ‘customer-forms’. If you don’t know what npm is 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; the second one is ‘customer-forms.component.html’; next is ‘customer-forms.component.spec.ts’ which is a test file to test your code; the last one is ‘customer-forms.component.ts’ which is a 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 a 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;  
    }  
  
    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 created ‘customer-forms.service.ts’ with data and some useful methods. We need to add this service to our ‘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, we let Angular know that this file will be injected in other classes or components.

Now, let us 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)  
  {  
    this.form.value["SoftwareId"] = id.target.selectedOptions[0].value;  
    console.log(this.form.value["SoftwareId"]);  
    console.log(this.SoftwareData);  
  }  
}  

Here, passing values in the constructor is a dependency injection ‘privatecustomerRequestService : CustomerFormsService’.

Angular is built upon a 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 the constructor.
 
Use the command npm install bootstrap to install the bootstrap in your project and add bootstrap to the angular.json file.
"styles": [  
              "node_modules/bootstrap/dist/css/bootstrap.min.css",  
              "src/styles.css"  
            ]  

In the ‘customer-forms.component.html’ file, 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 the "Save" button, you should see a console window in your browser. See if the object is logged or not.