Today in this tutorial we will look at the communication between component, model and service in our angular application. we have already created the required components, models and services in the previous part of this tutorial. Please have a look at this link if you have not created it: Part 3 Link. So, in this tutorial we will create a simple form to add name and address and then show them in the table. User will also be able to edit and delete the details provided. Although, in real application we will use web api to store and retrieve the required data, the scope of this tutorial is to provide the basic understanding of the communicaton in angular application so we will just store the data in array and will not use any server side application(like .net, java ,php etc). The output of the application that we are trying to build will looks like:

In this application we will have a simple bootstrap form in the left side for adding id, name , and address of a user and in the right side we can see the table showing the saved users. Moreover the user can also edit or delete the information. at the end of this tutorial we will create an angular application to perform this basic functionality. let us use bottom up approach to build this application. i.e we will start by creating model, service and then the UI. however you can follow the reverse process as well, the choice is yours. To start, let us add the attributes inside the Model, that we created previously.
Open user.model.ts file and then add attributes in it as shown below:
export class User {
public id:number=0;
public name:string;
public address:string;
}
Now, let us add required atrributes and functions inside our Service(user.service.ts) file. Before doing so, let us first evaluate the requirement of our application. Basically our application must be able to add User, edit user, and deleteUser. So, we will create 3 functions for doing these operation. Beside we will need 2 other attributes to store the data, one for storing the list of added users and another attribute for storing the current values of the form for model binding. So the service file might look like this.
import { Injectable } from '@angular/core';
import { User } from '../models/user.model';
@Injectable({
providedIn: 'root'
}
export class UserService {
public user:User=new User();
public userList=[ ];
constructor() {
}
public addUser(user:User){
var usr=new User();
usr.name=user.name;
usr.address=user.address;
usr.id=user.id;
this.userList.push(usr);
}
public editUser(user:User){
var temp=this.userList.filter(x=>x.id==user.id)[0];
temp.name=user.name;
temp.address=user.address;
}
public deleteUser(user:User){
var index=this.userList.findIndex(x=>x.id===user.id);
this.userList.splice(index,1);
}
}
Now, moving all let us not design the form required for our application. But before doing so, we must make an import of FormsModule in app.module.ts file. Similarly add UserService in providers. So, our app.module.ts file might look like below:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from "@angular/forms";
import { HttpClientModule } from "@angular/common/http";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UserComponent } from './components/user/user.component';
import { UserService } from './service/user.service';
@NgModule({
declarations: [
AppComponent,
UserComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [UserService],
bootstrap: [AppComponent]
})
export class AppModule { }
After adding the required imports let us not design UI for our application. for this open user.component.html file and add the following lines in it:
<div class="container">
<div class="row">
<h1>Angular Form Example(everestparked.com)</h1>
</div>
<hr>
<div class="row">
<div class="col-md-6">
<form #form="ngForm" autocomplete="off">
<div class="form-group">
<label for="Id">Id</label>
<input type="text" name="Id" [(ngModel)]="service.user.id" class="form-control" placeholder="Enter Id">
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="Name" [(ngModel)]="service.user.name" class="form-control" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="name">Address</label>
<input type="text" name="Address" [(ngModel)]="service.user.address" class="form-control" placeholder="Enter Address">
</div>
<button type="button" class="btn btn-sm btn-primary" (click)="onSubmit()"> Submit</button>
<button type="button" class="btn btn-sm btn-warning" (click)="resetUser()"> Reset</button>
</form>
</div>
<div class="col-md-6">
<table class="table table-bordered table-hovered">
<tr class="bg-success">
<td>Id</td>
<td>Name</td>
<td>Address</td>
<td>Action</td>
</tr>
<tr *ngFor="let item of service.userList">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.address}}</td>
<td>
<button class="btn btn-sm btn-outline btn-primary" (click)="editClicked(item)"><i class="far fa-edit"></i> Edit</button>
<button class="btn btn-sm btn-outline btn-danger" (click)="deleteClicked(item)"><i class="far fa-trash-alt"></i> Delete</button>
</td>
</tr>
</table>
</div>
</div>
</div>
Similarly, let us also have a look at user.component.ts file.
import { Component, OnInit } from '@angular/core';
import { UserService } from 'src/app/service/user.service';
import { NgForm } from '@angular/forms';
import { User } from 'src/app/models/user.model';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
public isEdit:Boolean=false;
constructor(private service:UserService) { }
ngOnInit() {
console.log(this.service.user);
}
onSubmit(){
if(this.isEdit){
this.service.editUser(this.service.user);
this.isEdit=false;
this.resetUser();
}else{
this.service.addUser(this.service.user);
this.resetUser();
}
}
editClicked(item:User){
this.service.user.name=item.name;
this.service.user.address=item.address;
this.service.user.id=item.id;
this.isEdit=true;
}
deleteClicked(item){
var result=confirm("Are you sure you want to delete this user?");
if(result){
this.service.deleteUser(item);
}
}
resetUser(){
this.isEdit=false;
this.service.user.id=0;
this.service.user.name="";
this.service.user.address="";
}
}
Now, let us try to understand the flow between user.component.ts and user.component.html file. first of all let us start with user.componet.ts file we can see the UserService named "service" being injected through the constructor. so, we can now use service in both user.component.ts and user.component.html file. now in our user.component.html file there is basically 2 parts the first is the form and the second is the table. now let's evaluate the form part. In the form part as you can see the form tag has #ngform. The next thing we can see is the tag like [(ngModel)]="service.user.name" in input fields.[(ngModel)] tells the angular app that this is model binding. to understand this first of all let us have a look at the value field. so what do we have in value field? there is service.user.name. so what do this mean? well, what angular do by looking this is it first check if there is any variable named service in user.component.ts file (which is corresponding .ts file for user.component.html), and it sees a variable named service that is injected in constructor of type UserService. so in the next step it checks if that service object has user attribute inside it or not and it finds it because UserService has user attribute. similarly, it again checks if user attribute of service has name attribute inside it or not. and yes it has ! so, whatever is the value of service.user.name the same value is shown here. Similarly, if user types some value in this field. it gets updated in the corresponding variable. for example, in our case, in the user.model.ts file the id attribute is initialized to 0. so, in the beginning, when the form is loaded we can see the value of 0 in the input field of Id. Now, whenever the user type any value in id field (say user typed 5 ). the corresponding value in service.user.id also changes. so now, if we print the value of service.user.id in our .ts file we will see the value 5 being printed. this concept is called model binding i.e whatever the value on model the same is in the view and vice-versa.
Now, moving on in the bottom of the form there are 2 buttons "Submit" and "Reset". and in these buttons there is an event defined using (click) property. here we have 2 values inside these events namely onSubmit() and resetUser(). So, whenever the user clicks submit button, onSubmit( ) function in user.component.ts file gets executed and whenever the user clicks reset button, resetUser() function in user.component.ts file gets executed. now inside these functions the respected operations are performed. Moreover these functions calls service to perform the required operation.
Similarly, in the second part of our user.component.html file there is table to display the stored user value. All are simple html table except the *ngFor="let item of service.userList" in the second row (tr) of the table. this is called looping. And how does it work? you may ask. so, in the first step angular locates the array which is service.userList . And since this expression is present in <tr> tag so <tr> tags gets repeated for n number of times (which is the number of items in service.userList) . similarly inside <td> tag we can see something like {{item.name}}. So, what is this? this is called interpolation. now you may ask, what is this item mean? this item is the individual user inside service.userList (since service.userList is the list of users). for example, let us say service.userList is the list of 4 users(say user1,user2....). now, whenever {{item.name}} is executed . in the first line user1.name is executed and so on for other 4 users. and this concept of showing value of item using double curly braces is called interpolation.
In this way, in this tutorial we saw the concept of communication between components, model and service in our angular app. in regular angular apps all of the concepts are the same as here except in the service where we will make api calls to store and retrieve the data. but, since the scope of this article was just to provide the basic communication, so we just stored them in array in service and then used simple javascript function to add, edit and delete. we will study about api call in futher articles so please, stay tuned.