How to create a form in angular

In this tutorial we will learn how to create a form in angular 7 application. We will make a form like below.

angular-form-contact-form

Before we head to create the form, let’s understand the basics:

There are 2 types of forms :
1. Template driven forms
2. Model driven or Reactive forms 

1. Template driven forms

The template driven approach makes use of built-in directives to build forms such as ngModelngModelGroup, and ngForm available from the FormsModule module.

When to use ?

  • where forms are small
  • Simple validations
  • migrating from angular 1 to angular 2

Advantage:

  • easier to create
  • less code

2. Model driven or Reactive forms

The model driven approach of creating forms in Angular 6 makes use of FormControlFormGroup and FormBuilder available from the ReactiveFormsModule module.

When to use ?

  • Where forms are big
  • validations are complex

Reactive forms have majorily two classes:

  • FormGroup : can be considered as a collection of FormControls and other FormGroups
  • FormControl : to bind the properties with the html elements

At first, we will create an instance of FormGroup class and link it to the html form. Then, we will create a number of instances of FormControl as many number of form elements.

Let’s Begin !

Step 1: Registering the reactive forms module in app.module.ts

 import { ReactiveFormsModule } from '@angular/forms';

and

 imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule ], 

Step 2: Creating a FormGroup in app.component.ts

import { Component, OnInit } from '@angular/core';
import {FormGroup, FormControl} from '@angular/forms';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
  title = 'my-dream-app';
  contactForm : FormGroup;
  
  constructor(){}
  ngOnInit(){
    this.contactForm = new FormGroup({
      name: new FormControl(),
      email: new FormControl()
    });
  }
  
  onSubmit(): void{
    console.log(this.contactForm.value);
  }
}

we will print the values entered in the form to the console log.

Step 3: Associating FormGroup with the HTML view

<div class="col-lg-4" >
  <form [formGroup]="contactForm" (ngSubmit)="onSubmit()" class="form-horizontal">
    <h3 class="panel-title">Contact Form</h3>
    <div class="form-group">
      <label>Name</label>
      <input id="name" formControlName="name" type="text" class="form-control">
    </div>
    <div class="form-group">
      <label>Email</label>
      <input id="email" formControlName="email" type="text" class="form-control">
    </div>
    <div>
      <button type="submit" class="btn-primary">Submit</button>
    </div>
  </form>
</div>

Output

angular-form-contact-form-output

Summary

In this tutorial, we learnt about how to create a form in angular application and different types of form.
Hope you liked it!


How to create a component in angular

In this tutorial we will understand how to create a component in angular application. We have already seen what is an angular component though, but we will look into it again. In Angular each functionality can be made as a component which can be used in the entire application just by importing it. So now we will look into the steps to create a component in angular.

Let’s Begin ! – Just 2 Steps

Step 1 :

create a new directory inside app directory for better management of components(not mandatory)

> mkdir contact

Step 2 :

Now, create component by using command as below

> ng g c contact –flat

-g : to generate

-c : for component

–flat in an option used to stop create a directory of same name as the name given in the above command, and create all files in the current directory. It puts the file in src/app instead of its own folder.

So the above command creates 4 files as shown below in this snapshot.

create-angular-component-using-angular-cli

This creates 4 files :

contact.component.html file : file write the html content of your page exists.

contact.component.spec.ts : file where you have the test cases

contact.component.ts : file where you write the functionality and logics in this typescript.

contact.component.css : file where you write the css content of the page.

 Next, Include this component in main app.component.html 

by including the tag in app.component.html as per the selector created in contact.component.ts

<app-contact></app-contact>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

Summary

In this tutorial, we learnt how to create a component in angular application and add the created component using its html selector tag to any other component like AppComponent here. Enjoy learning Angular.
Hope you liked it!


How to add bootstrap and other js in angular application

In this tutorial we will understand how to add bootsrap css in angular app.

After creating the angular basic app using ng new my-dream-app install the bootstrap using the below command.

1. Install bootsrap using npm cli

> npm install bootstrap –save

Type this command from your project directory eg: (c:\workspace\my-dream-app)

install-bootstrap-css-in-angular

Note: In case you see a Warning as below in the snapshot, it means you need to navigate to your project structure and then execute the bootstrap install command, if you see a warning of package.json no such file warning it simply means you must install bootstrap from this directory where the file is present.

install-bootstrap-css-in-angular

2. Add bootstrap css entry in angular.json

Open angular.json file, locate styles and add bootstrap file path to the styles section. Like this,

angular-json-styles-add-bootstrap

3. Verify – bootstrap has been installed successfully or not?

Let’s add a table with few extra bootstrap classes to see bootstrap is working fine or not

In your app.component.html

add the following html table code:

<div class="container">
  <table class="table table-dark table-hover table-striped">
    <thead class="thead-light">
      <tr>
        <th>Name</th>
        <th>Age</th>       
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Jack</td>
        <td>30</td>
      </tr>
      <tr>
        <td>Jill</td>
        <td>31</td>       
      </tr>
      <tr>
        <td>Robert</td>
        <td>32</td>       
      </tr>
    </tbody>
  </table>
</div>

Now You would see this in your browser: localhost:4200

angular-bootstrap-css-table

AND earlier without Bootstrap, it would look like as shown below:

angular-table-without-bootstrap-css

Summary

In this tutorial, we learnt about how to add bootstrap in angular project and how to make use of it by adding a simple bootsrap css classes in html table, Enjoy using bootstrap with angular now, it makes life easier.
Hope you liked it!


Angular app Files and its explanation / Files Explanation

In this tutorial we will understand the angular file-structure of a project and see each default file, folder created and its uses.

angular-project-file-structure-visual-studio-code

Files used in Angular 7 App folder

  • src folder: This is the folder which contains the main code files related to your angular application.
  • app folder: The app folder contains the files, you have created for app components.
  • app.component.css: This file contains the cascading style sheets code for your app component.
  • app.component.html: This file contains the html file related to app component. This is the template file which is used by angular to do the data binding.
  • app.component.spec.ts: This file is a unit testing file related to app component. This file is used along with other unit tests. It is run from Angular CLI by the command ng test.
  • app.component.ts: This is the most important typescript file which includes the view logic behind the component.
  • app.module.ts: This is also a typescript file which includes all the dependencies for the website. This file is used to define the needed modules to be imported, the components to be declared and the main component to be bootstrapped.
  • e2e folder: end-to-end testing files for the project are contained here.

Other Important files

  • package.json: This is npm configuration file. It includes details about your website’s package dependencies along with details about your own website being a package itself.
  • package-lock.json: This is an auto-generated and modified file that gets updated whenever npm does an operation related to node_modules or package.json
  • angular.json: It is very important configuration file related to your angular application. It defines the structure of your app and includes any settings associated with your application. Here, you can specify environments on this file (development, production). This is the file where we add Bootstrap file to work with Angular 7.
  • .gitignore: This file is related to the source control git.
  • .editorconfig: This is a simple file which is used to maintain consistency in code editors to organize some basics such as indentation and whitespaces.
  • assets folder: This folder is a placeholder for resource files which are used in the application such as images, locales, translations etc.
  • environments folder: The environments folder is used to hold the environment configuration constants that help when building the angular application. The constants are defined in 2 separate .ts files (environment.ts and environment.prod.ts), where these constants are used within the angular.json file by the Angular CLI. For example, if you run the ng build command, it will build the application using the development environment settings, whereas the command ng build ?prod will build the project using the production environment settings.
  • browserslist: This file is used by autoprefixer that adjusts the CSS to support a list of defined browsers.
  • favicon.ico: This file specifies a small icon that appears next to the browser tab of a website.
  • index.html: This is the entry file which holds the high level container for the angular application.
  • karma.config.js: This file specifies the config file for the Karma Test Runner, Karma has been developed by the AngularJS team which can run tests for both AngularJS and Angular 2+
  • main.ts: As defined in angular.json file, this is the main ts file that will first run. This file bootstraps (starts) the AppModule from app.module.ts , and it can be used to define global configurations.
  • polyfills.ts: This file is a set of code that can be used to provide compatibility support for older browsers. Angular 7 code is written mainly in ES6+ language specifications which is getting more adopted in front-end development, so since not all browsers support the full ES6+ specifications, pollyfills can be used to cover whatever feature missing from a given browser.
  • styles.css: This is a global css file which is used by the angular application.
  • tests.ts: This is the main test file that the Angular CLI command ng test will use to traverse all the unit tests within the application and run them.
  • tsconfig.json: This is a typescript compiler configuration file.
  • tsconfig.app.json: This is used to override the tsconfig.json file with app specific configurations.
  • tsconfig.spec.json: This overrides the tsconfig.json file with app specific unit test configurations.

Summary

In this tutorial, we learnt about the file structure of the angular application, it’s various files and folder structures and the type of information it stores.
Hope you liked it!