Creating Angular Application using bootstrap

Hey readers, in this article we will get little deeper into angular by creating a simple web application where a user is posting status and having likes and dislikes on the post. For building this application we are going to create an angular application using bootstrap.

Social Application

Before reading this article I highly recommend you to first cover two of my previous article. Getting Started With Angular and How to create Angular Application using Angular CLI


Note: We will be using Typescript in this application. If you are new to Typescript don’t have to worry, if you have a basic knowledge of OOPS and JavaScript, you will easily grasp the code. We will cover for you typescript basics in upcoming articles.

If you have covered the given links and have installed Node.js, then use the following npm command to install typescript globally

npm install -g typescript

After installation, lets now create our application using angular CLI, let’s name this application Social

ng new Social

After application successfully created by angular CLI, run cd social in terminal to switch into this directory and type code .(dot) and press enter, this will open the application in VS Code or open in your favourite editor. We are also going to add bootstrap and font-awesome as we are going to design our form using them. So after switching into Social directory run the following commands.

npm install bootstrap
npm install font-awesome

If you now look into node_modules folder in our Social application, you will find both bootstrap and font-awesome directory present containing all the required files. Also if you open package.json file, bootstrap and font-awesome packages are defined under dependencies.

Avatar
Download this image and name it Avatar.png and place it under Assets/Images folder.
Ok so now we have all the required things to start implementation of our requirement. Open app.component.html file, remove the existing code and paste the following html.


<div class="container">
  <form class="card border-success">
    <div class="card-header  text-success">
      <h4 class="card-title">Compose Post</h4>
    </div>
    <div class="card-body">
      <textarea rows="4" class="form-control" placeholder="What's in your mood..." name="status"></textarea>
    </div>
    <div class="card-footer" style="text-align: center">
      <button class="btn btn-outline-success" style="width:10%">Post</button>
    </div>
  </form>

  <hr>

  <div class="card border-success">
    <div class="card-header  text-success">
      <h4 class="card-title">Feed</h4>
    </div>
    <div class="card-body">
      <div class="row" style=" margin-bottom: 20px">
        <div class="col-md-2" style="text-align: right;">
          <img src="assets/Images/Avatar.png" style="height: 60px; width: 60px">
        </div>
        <div class="col-md-6">This is a sample content. Once the user writes in the above text box and click on Post button. It will be reflected here.</div>
        <div class="col-md-1" style="text-align: right;">0</div>
        <div class="col-md-1">
          <a class="text-success" href>
            <i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
          </a>
        </div>
        <div class="col-md-1" style="text-align: right;">0</div>
        <div class="col-md-1">
          <a class="text-danger" href>
            <i class="fa fa-thumbs-o-down" aria-hidden="true"></i>
          </a>
        </div>
        
      </div>
    </div>

  </div>

</div>

In the HTML, under form tag, we have taken one textbox and one button. A user will write in the textbox and clicks on post button. The content of the textbox will be listed below with likes and dislikes icon.

The design is now ready for you, but before running our application to check, we have to do one more thing. We need to add reference of bootstrap and font-awesome that is stored under node_modules folder. Open .angular-cli.json file and paste the following code under styles array.

"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"../node_modules/font-awesome/css/font-awesome.min.css",
"styles.css"
]

Now from terminal execute ng serve -o to run our application into our default browser. The html will render as below.

Social 1

Let’s now add some behavior in the form. User when fill in the textbox and clicks on button to submit, print the content of the textbox in the browser console. So to do this first let modify the textarea and button element as given below.

<textarea rows="4" class="form-control" placeholder="What's in your mood..." name="status" #newstatus></textarea>

<button class="btn btn-outline-success" style="width:10%" (click)="addPost(newstatus)">Post</button>

In the button element we have binded addPost function on click event, so lets define addPost function under app.component.ts. Update the AppComponent class with the given snippets.


export class AppComponent {
  addPost(status: HTMLInputElement): boolean {
    console.log(`Your status : ${status.value}`);
    status.value = '';
    return false;
  }
}

What we have done above, in the textarea we have added attribute #newstatus. # (hash) tells angular to assign those tags to a local variable, so newstatus variable is available wintin this view and is of type object that represents textarea input DOM element (HTMLInputElement), and we can access the value of this input tag using newstatus.value.

On the button element we have added (click) attribute that calls the function addPost when button click event is fired. #newstatus variable is passed to the addPost function.

In app.component.ts, under component class AppComponent, addPost function is defined that takes one argument status of type HTMLInputElement, remember that on view we are passing #newstatus, object of type HTMLInputElement. So this argument has the data that is passed from the view, to print the value of the textbox in console we are using this argument status.value in the function and console.log the value and empty the input field.

Note: We are using the backtick strings. This is a new feature of ES6 that allows us to do multiple line strings and can put templates and expressions inside this.

Let’s test our work now. Fill in the textbox and press the Post button, launch developer tools pressing F12 key on the keyboard, switch to console tab, and watch
Console

So, we are now successfully reads the textbox value. Our next move is to add this value into list and display them below the form as per our design. To do that lets create a new component. The purpose of this component will be to display the list of status. If the ng serve -o command is running, press ctrl + c, type y and hit enter, this will terminate the compilation. Now write the following CLI command to generate component naming list-of-status.

ng generate component list-of-status

or,

ng g c list-of-status

Now open list-of-status.component.html and replace the content with the following

<div class="col-md-2" style="text-align: right;">
  <img src="assets/Images/Avatar.png" style="height: 60px; width: 60px">
</div>
<div class="col-md-6">This is a sample content. Once the user writes in the above text box and click on Post button. It will be reflected here.</div>
<div class="col-md-1" style="text-align: right;">0</div>
<div class="col-md-1">
  <a class="text-success" href>
    <i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
  </a>
</div>
<div class="col-md-1" style="text-align: right;">0</div>
<div class="col-md-1">
  <a class="text-danger" href>
    <i class="fa fa-thumbs-o-down" aria-hidden="true"></i>
  </a>
</div>

Back to the app.component.html, replace the html under div element having class card-body as below

<div class="card-body">
      <app-list-of-status class="row" style=" margin-bottom: 20px">
      </app-list-of-status>
 </div>

What we have done is we have moved the content under div element having class row from app.component.html to the list-of-status.component.html and rename this div with app-list-of-status selector. The selector is defined in the list-of-status.component.ts that we have just generated. Run the application now and you will notice that the application is running same as before.

Next we are creating a model, it is better to define our logic in a separate class. Create a new file naming Post.model.ts under list-of-status folder and paste the following code.


export class Post {
status: string;
likes: number;
dislikes: number;

constructor(status: string, likes?: number, dislikes?: number) {
this.status = status;
this.likes = likes || 0;
this.dislikes = dislikes || 0;
}

like(): void {
this.likes += 1;
}

dislike(): void {
this.dislikes += 1;
}
}

We have taken 3 variables each post will have status, likes, and dislikes. The constructor will initialize these variables, likes and dislikes are of type number so default set to 0. like and dislike function will increase the count of likes and dislikes by 1.
Now open list-of-status.component.ts and import Input property from @angular/core and import model Post from post.model. The code will look like this


import { Component, OnInit, Input } from '@angular/core';
import { Post } from './Post.model';

Update ListOfStatusComponent class on the same page with the following code:


export class ListOfStatusComponent implements OnInit {
@Input() post: Post;

constructor() { }

like(): boolean {
this.post.like();
return false;
}

dislike(): boolean {
this.post.dislike();
return false;
}

ngOnInit() {
}
}

Open list-of-status.component.html and replace the html with the below given html

<div class="col-md-2" style="text-align: right;">
  <img src="assets/Images/Avatar.png" style="height: 60px; width: 60px">
</div>
<div class="col-md-6">{{post.status}}</div>
<div class="col-md-1" style="text-align: right;">{{post.likes}}</div>
<div class="col-md-1">
  <a class="text-success" href (click)="like()">
    <i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
  </a>
</div>
<div class="col-md-1" style="text-align: right;">{{post.dislikes}}</div>
<div class="col-md-1">
  <a class="text-danger" href (click)="dislike()">
    <i class="fa fa-thumbs-o-down" aria-hidden="true"></i>
  </a>
</div>

What we have done in ListOfStatusComponent class is like and dislike function are defined calling their respective like and dislike function that is defined in the model. The model is assigned to the property with Input decorator.
The Input() property is a settable property annotated with a @Input decorations and model Post is assign to it naming this property post. Value from the parent component will flow to this property when its member are property binded on the view in app.component.html. On the view list-of-status.component.html, like and dislike function of the post property are binded on click event to the respective like and dislike anchor element, and a number of likes and dislikes of the post property are displayed using double curly brace interpolation.

In app.component.ts, we are going to call our model and create a variable of type Array of Post, under constructor we will be initializing this array with some data. The code will look like this


import { Component } from '@angular/core';
import { Post } from './list-of-status/Post.model';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
posts: Post[];

constructor() {
this.posts = [
new Post('Angular is awesome', 3, 1),
new Post('Everyone should learn Angular', 1, 0),
];
}

addPost(status: HTMLInputElement): boolean {
console.log(`Your status : ${status.value}`);
status.value = '';
return false;
}
}

Now open app.component.html and use *ngFor to iterate over array of post and property bind each post, this property binding will pass data from source to view.


<app-list-of-status class="row" style=" margin-bottom: 20px" *ngFor="let post of post" [post]="post">
</app-list-of-status>

Watch the page on browser now. The page is now rendering list of status that we have defined in the list. Press the likes and dislikes icon it will increase the value of number of likes and dislikes. Try to post after filling the textbox, oops it has not been add in the list. Remember we are just console.log the post. Now lets update the addPost function to add the textbox content in the list.


addPost(status: HTMLInputElement): boolean {
console.log(`Your status : ${status.value}`);
this.posts.push(new Post(status.value, 0, 0));
status.value = '';
return false;
}

Now, try adding content on the textbox and submit, it has successfully added and also likes and dislikes are working fine.

So in this article, we have covered how to use third-party libraries like bootstrap and font-awesome, how to add a component and how to use model. At the moment we are not using any database, but in real world application we require database. In upcoming articles we will definitely cover working with database and many more things, so stay tuned and subscribe to our blog. Thanks for reading.

Download Source Code from github: Social

Share Knowledge

About Pankaj Kumar Singh

Learn, Share and Discuss.
This entry was posted in ANGULAR and tagged , , , , , , , . Bookmark the permalink.

3 Responses to Creating Angular Application using bootstrap

  1. Pingback: ASP.NET MVC - Custom 404 page for invalid request - code-adda

  2. Pingback: Deploy Angular App On Tomcat Server - code-adda

  3. Pingback: How to deploy angular application on IIS Server - code-adda

Leave a Reply

Your email address will not be published. Required fields are marked *