Angular Blog Posting App Tutorial

Hello everyone, we hope you all are doing well. After a full article-based tutorial playlist, we’ve come up with a hands-on app to make your concepts clearer, and you’ll also understand which concept to be applied where.

Angular Tutorial – Blog Posting Application

In this article, we will create a Blog Posting application using Angular. This will be a very basic level app specially designed for beginners who have just completed learning Angular.

Firstly, let’s take a short overview of the app.

Home Page Wireframe

angular application home page overview viewframe

Add Blog Page Wireframe

angular application add post viewframe

In the app, we’ll be having a homepage where all the blogs will be displayed, and we’ll also have an add-blog feature that will redirect to the add-blog component where we’ll write our blogs and upload them as shown in the above picture.

Now let’s move and create the app.

Step 1: Create an Angular app with a name

ng new blog-posting-app

Step 2: Generate three components with name home, add-blog, and page-not-found

ng g c MyComponents/home
ng g c MyComponents/add-blog
ng g c MyComponents/page-not-found

MyComponents is a folder inside which we’ll be keeping all our created components. It’s indeed a good practice.

Step 3: Configure the routes

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddBlogComponent } from './MyComponents/add-blog/add-blog.component';
import { HomeComponent } from './MyComponents/home/home.component';
import { PageNotFoundComponent } from './MyComponents/page-not-found/page-not-found.component';

const routes: Routes = [
  {path:'',redirectTo:'/home', pathMatch:'full'},
  {path:'home', component:HomeComponent},
  {path:'add-blog', component:AddBlogComponent},
  {path:'**', component:PageNotFoundComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }
export const routingComponents=[HomeComponent,AddBlogComponent,PageNotFoundComponent]

module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    routingComponents,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

component.html

<router-outlet></router-outlet>

NOTE: We strongly recommend looking into our Routing articles to understand the routing part in detail.

Step 4: Generate a service to supply data in each component

ng g s services

services.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class ServicesService {
  constructor() { }

  getBlogs(){
    return localStorage.getItem('blogs')
  }
}

Register the service to module.ts and add it into the “providers” array.

providers: [ServicesService]

NOTE: We strongly recommend looking into our Using a Service article to understand this part in detail.

Step 5: Complete the add-blog component

add-blog.component.html

<form action="" [formGroup]="myform">
  <div>
    <label for="title">Title:</label>
    <input type="text" id="title" placeholder="Enter your title" class="input" name="title" formControlName="title">
  </div>
  <div>
    <label for="blog">Content:</label>
    <textarea name="blog" id="blog" cols="30" rows="10" placeholder="Enter your blog content here." class="input" formControlName="blog"></textarea>
  </div>
  <div>
    <label for="name">Created By:</label>
    <input type="text" id="name" placeholder="Enter you name" class="input" name="name" formControlName="name">
  </div> 
  <button [disabled]="!myform.valid" (click)="submit()">ADD BLOG</button>
  <button routerLink="/home">BACK</button>
</form>

add-blog.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder,Validators } from "@angular/forms";
import { ServicesService } from 'src/app/services.service';

@Component({
  selector: 'app-add-blog',
  templateUrl: './add-blog.component.html',
  styleUrls: ['./add-blog.component.css']
})

export class AddBlogComponent implements OnInit {

  localItem : any
  form = {}
  blog = [{}]

  constructor(private fb:FormBuilder,private service:ServicesService) { }

  ngOnInit() : void { }

  myform = this.fb.group({
    name : ['', Validators.required],
    title : ['', Validators.required],
    blog : ['', Validators.required]
  })

  submit(){
    this.form = this.myform.value
    this.localItem = this.service.getBlogs()
    this.blog = JSON.parse(this.localItem)
    this.blog.push(this.form)
    localStorage.setItem('blogs', JSON.stringify(this.blog))
  }
}

We’ve used form builder to create the add blog form.

NOTE: We strongly recommend looking into our REACTIVE FORMS USING FORM BUILDER AND VALIADATORS article to understand this part in detail.

  • We’re getting the data from the service and storing it into the array, and then pushing the new blog into it. And then we’re converting it into String using stringify() and storing it into localStorage.
  • We’re using localStorage as data storage.

Local Storage: It stores data into the browser and doesn’t get deleted when the browser is closed and has no expiry date. It has three functions:

  1. localStorage.setItems(‘key’, ‘String’): It is used to store data into the browser storage.
  2. localStorage.getItems(‘key’): It is used to get any key data from the storage.
  3. localStorage.clear(): It is used to clear the storage.

Step 5: Complete the home component

home.component.html

<h1>Today:{{today | date}}</h1>
<div>
  <h2>Blogs</h2>
  <button routerLink="/add-blog">ADD BLOG</button>
</div>
<ul *ngFor="let blog of blogs">
  <li>Title: {{blog.title}}</li>
  <li>Blog: {{blog.blog}}</li>
  <li>Created by: {{blog.name}}</li>
</ul>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { ServicesService } from 'src/app/services.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
  localItem:any
  blogs = []
  today:number = Date.now()

  constructor(private service:ServicesService) { }

  ngOnInit():void {
    this.localItem = this.service.getBlogs()
    this.blogs=JSON.parse(this.localItem)
  }
}
  • Here we’re getting the data using service and storing it into an array after parsing it using parse().
  • And in the HTML file, we’re displaying the data using ngFor directive and interpolation.

NOTE: We strongly recommend looking into our ngFor Directive in Angular and INTERPOLATION IN ANGULAR article to understand the displaying into view part in detail.

Step 6: Complete the page-not-found component

page-not-found.component.html

<h2>Error!! Page Not Found</h2>

Here we’ve used the concept of wild card routing; the concept is that if any user searches for any component that doesn’t exist will see the message Error!! Page Not Found into the view.

NOTE: We strongly recommend looking into our WILD CARD ROUTING IN ANGULAR article to understand this part in detail.

Let’s see the output part of our app now

Outputs

add-blog component

angular add blog post page

In the add-blog component, initially, the ADD BLOG button will be disabled so that no empty blog gets stored. After the user fills every field, the button will be enabled, and on clicking the button, the data will be stored. It also has a back button that will take the user to the home component on clicking.

home-component(initially)

angular home page for blog post app

Initially, we’ve some blogs posted in the home component. Now let’s see the result after adding one more blog.

home-component(finally)

angular home page final for blog post app

We can see clearly that the blog got added successfully in the home component. We also have an ADD BLOG button which on clicking will take the user to the add-blog component.

Now, what if any user searches for some random unavailable components, localhost:4200/home1 (let’s say).

We’ve used wild card routing to handle that. So, let’s see the output of that also. Here, we searched for localhost:4200/home1 and got the expected error into the view.

 

angular error 404 page not found template

And the last part, let’s check the browser’s localStorage if our data is successfully stored or not.

angular localstorage console view

We can clearly see that data is stored successfully in the browser’s storage.

So, this is it. This was a fundamental app with very minimal features in it. Also, we haven’t given any priority to the styling part. You can add CSS code to do the styling of your own choice.

Conclusion

We hope this article made you understand how a real-world application works and how to use different features of Angular in different scenarios.

After going through this article, we strongly recommend creating this application following the mentioned steps to understand it more appropriately and face the errors and fix them to become a good developer.

Leave a Reply

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