0–100 in Angular: Part 2

Valentine Oragbakosi
Vannila
Published in
5 min readSep 29, 2019

In the first part of the series, we talked about setting up our angular environment and running it on a desirable port. In case you missed that, you can read more here. In this part, we would be building a simple list of staffs in a company and they email. We would use this simple application to learn the following

  1. Single data binding
  2. Form submit
  3. Data types
  4. Angular common modules
let’s get started

First, let me define the following terms listed above

Single Data Binding: In simple terms, this is a way to pass variables from your typescript component to your HTML component and updating the HTML DOM whenever the variable in your typescript changes.

Form Submit: This is a way of taking input from the user and submitting it to a central pool (in our case we would use an array).

Data Types: This is defining the data type our variable would accept eg string, Array<number>, object, any, etc.

Angular Common modules: This is a module that contains the *ngFor, *ngIf, and *ngSwitch directive. The name of the directives are quite self-explanatory. The *ngFor is used to iterate over a collection of items, *ngIf accepts a true or false data type and shows the DOM if true but hides it if false, while *ngSwitch uses the switch case we are familiar with.

Now let’s code

Now open your src/app/app.component.html clear everything inside except

<router-outlet></router-outlet>

This router outlet is important for our routing in the future so we want to keep it.

We would also want to create a new component and make it our landing page. Angular makes that very simple for us. Just open a terminal in your project directory and type the command

ng g c home

This would generate a home component in your src/app folder and add it as a declaration to your app.module.ts this would let the module know that you have a new component. If you open the home folder, you would see a couple of files created. The home.component.css file is where all our CSS for the home component goes, the home.component.html contains our home component Html, the home.component.spec.ts is for testing our home component while the home.component.ts is the typescript for our home component where all our logic goes.

Now let’s make it our landing page. The first thing to do is to import the home component into your src/app/app-routing.module.ts and add it as the base path like so

import { HomeComponent } from './home/home.component';const routes: Routes = [{
path:'',
component:HomeComponent
}];

This would tell Angular that we want to load this component when we are in the base URL of our application. If all works well, you should see a message that says “home works!” on your browser.

Now let’s start writing our employee list, shall we?

Now open your home.component.ts and declare a variable that would hold our list. Since this variable would hold a list of objects, we say

list:Array<object>

So now, Typescript knows to allow only objects in this array. After doing that, we would see very popular ngOnInt. This is Angular life cycle hook and what it does is to execute the code inside its curly braces whenever the component loads. And of course, we want to see our list when the component loads. So we add our array of objects inside of it as thus

ngOnInit() {this.list=[{name:"Chidi Emma",email:"chidi43@gmail.com"},{name:"Micheal Nwosu",email:"mike4real@yahoo.com"},{name:"Bisola Nkiru",email:"buka4short@yahoo.com"},]}

If all goes correctly, your home.component.ts file should look like this

import { Component, OnInit } from '@angular/core';@Component({selector: 'app-home',templateUrl: './home.component.html',styleUrls: ['./home.component.css']})export class HomeComponent implements OnInit {list:Array<object>constructor() { }ngOnInit() {this.list=[{name:"Chidi Emma",email:"chidi43@gmail.com"},{name:"Micheal Nwosu",email:"mike4real@yahoo.com"},{name:"Bisola Nkiru",email:"buka4short@yahoo.com"},]}}

Now let’s use our *ngFor directive to make sure we see all the list in our browser. And the easy way to do that is writing the following in our home.component.html.

<div><ul *ngFor="let i of list"><li>Name:{{i.name}}Email:{{i.email}}</li></ul></div>

If all goes well, we should see a list of names and emails on our browser. and just like that, we have our first Angular application (let’s throw a party).

Now let’s add the option of adding new names to the list via a form. And in this case, we would use Angular reactive form.

The first step is to add the form module to our app.module.ts and add it to our imports as such

//other code here
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
imports:[//other items hereFormsModule,ReactiveFormsModule]

This would let angular know that we want to use this form in our component. Now that we have that out of the way, let’s go ahead and use the form in our home.component.ts

  1. import the following in your home.component.ts
import { FormControl, Validators, FormGroup, FormBuilder} from '@angular/forms';

2. Add the form builder in your constructor as such

constructor(private fb:FormBuilder){}

This would prepare the form builder object to be used in our class.

3. Create a variable called myForm that would hold our form group just as we did for list, but this would have a data type of FormGroup

myForm:FormGroup

4. Create the form instance on initialization and add validation

this.myForm=this.fb.group({name:['', Validators.required],email:['', [Validators.email, Validators.required]]})

The empty quote tells the form to be empty on initialization and the validation on name says that name is a required field, while that on email says that email is also a required field that should be a valid email. This should be added in ngOnInt

5. Let’s create the function to call when we submit the form (this should be outside ngOnint)

submit(){var formValue=this.myForm.value;this.list.push(formValue)}

This takes the value from the form and append it to our array

6. Let’s make our app.component.html aware of this form and submit function. Create a form as thus:

<form (ngSubmit)="submit()" [formGroup]="myForm"><input type="text" formControlName="name" placeholder="name"><input type="email" formControlName="email" placeholder="email"><button [disabled]="myForm.invalid">submit</button></form>

There seems to be a lot happening here so let me explain. The ngSubmit is what tells the form which function to call when it wants to submit, the formGroup is what binds the Html form to the myForm form group in our typescript, the formControlName binds the form input to the names and validation we gave it in our typescript, while the disabled disables the button till the validations are met

If all works well, we should add names to the list and it would update to the DOM automatically without reloading the page. That’s the power of one-way data binding.

Since we updated our array, the data would also reflect in our list.

Now we can have a good grasp on many very important concepts in Angular. In your free time, update the code and make it able to delete names from the list. You can ask questions in the comment.

See you later

--

--

Valentine Oragbakosi
Vannila
Writer for

Programmer with interest in machine leaning, operating systems and the web