Should You Use Bootstrap?

Should You Use Bootstrap?

Should you use Bootstrap? What we should be asking is if we should use any CSS framework, and in this video I will be answering that question once and for all. What is Bootstrap. What to consider before using a CSS framework. When a CSS framework is a good choice. The negatives of using a CSS framework

Should you use Bootstrap? That is the age old question people have been asking since the beginning of Bootstrap's rise to popularity, but this question is even broader than just Bootstrap. What we should be asking is if we should use any CSS framework, and in this video I will be answering that question once and for all.

Obviously, this isn't as easy as yes or no since CSS frameworks can be really useful in some situations and terrible in others. In this video I will be covering all the most important things to consider when thinking about using a CSS framework and giving you my opinion on CSS frameworks as well.

ūü߆ Concepts Covered:

  • What Bootstrap is
  • What to consider before using a CSS framework
  • When a CSS framework is a good choice
  • The negatives of using a CSS framework

How to integrate Bootstrap 4 with Angular 9?

How to integrate Bootstrap 4 with Angular 9?

In this Angular 9 tutorial, we've seen different ways of integrating Bootstrap 4 in Angular 9 Apps. We will see how to use Bootstrap to style apps built using Angular 9.

In this tutorial, we will see how to use Bootstrap to style apps built using Angular 9.

We'll see how to integrate Angular with Bootstrap, in various ways including using ng-bootstrap and ngx-bootstrap packages.

We'll be using Angular CLI 9 for generating a brand new project.

These are the steps of our tutorial:

  • Step 1 - Installing Angular CLI v9
  • Step 2 - Installing Bootstrap 4 in Your Angular 9 Project
  • Step 3 (Method 1) - Adding Bootstrap 4 to Angular 9 Using angular.json
  • Step 3 (Method 2) - Adding Bootstrap 4 to Angular 9 Using index.html
  • Step 3 (Method 3) - Adding Bootstrap 4 to Angular 9 Using styles.css
  • Alternative Step - Adding Bootstrap 4 Using ng-bootstrap and ngx-bootstrap
What is Bootstrap

Bootstrap is the most popular HTML and CSS framework for building responsive layouts with ease and without having a deep knowledge of CSS (Still custom CSS is required to customize your design ane make it different from the other Bootstrap-styled websites unless you are using a BS theme developed specifically for you).

Bootstrap 4 is the latest version of BS which brings many new and powerful features to the framework most importantly Flexbox which is now the default display system for BS grid layout (one of the most important features of BS).

3+ Ways to Include Bootstrap 4 In Your Angular Project

This can be done in multiple ways:

  • Including the Bootstrap CSS and JavaScript files in the <head> section of the index.html file of your Angular project with a <link> and <script> tags,

  • Importing the Bootstrap CSS file in the global styles.css file of your Angular project with an @import keyword.

  • Adding the Bootstrap CSS and JavaScript files in the styles and scripts arrays of the angular.json file of your project

Step 1 - Installing Angular CLI v9

Let's get started by installing Angular CLI v9 if it is not yet installed on your machine.

Head over to a new command-line interface and run the following command to install the latest version of the Angular CLI:

$ npm install -g @angular/[email protected]

At the time of writing this tutorial, Angular 9 is still in pre-release, so we need to use the next tag to install it. Angular v9.0.0-rc.2 is installed.

Note: This will install the Angular CLI globally on your system so depending on your npm configuration you may need to add sudo (for superuser access) in macOS and Linux or use a command prompt with admin access in Windows.

After the installation, you'll have at your disposal the ng utility. Let's use it to generate a new Angular 9 project.

$ ng new angular-bootstrap-examples

You will be prompted for a couple of questions:

? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? (Use arrow keys)
> CSS
  SCSS   [ https://sass-lang.com/documentation/syntax#scss                ]
  Sass   [ https://sass-lang.com/documentation/syntax#the-indented-syntax ]
  Less   [ http://lesscss.org                                             ]
  Stylus [ http://stylus-lang.com                                         ]

Most importantly, choose CSS as the stylesheet format because we'll use ths CSS version of Bootstrap in our tutorial.

The command will generate the directory structure and necessary files for the project and will install the required dependencies.

Next, navigate inside the root folder of your project

$ cd angular-bootstrap-examples

You can then serve your Angular 9 application using the ng serve command as follows:

$ ng serve

Your app will be served from http://localhost:4200/

Step 2 - Installing Bootstrap 4 in Your Angular 9 Project

In this step, we'll proceed to add Bootstrap 4 to our Angular 9 application.

There are various ways that you can use to install Bootstrap in your project:

  • Installing Bootstrap from npm using the npm install command,
  • Downloading Bootstrap files and adding them to the src/assets folder of your Angular project,
  • Using Bootstrap from a CDN.

Let's proceed with the first method. Go back to your command-line interface and install Bootstrap 4 via npm as follows:

 $ npm install --save bootstrap

This will also add the bootstrap package to package.json.

As the time of writing this tutorial, bootstrap v4.3.1 will be installed.

The Bootstrap 4 assets will be installed in the node_modules/bootstrap folder. You'll need to tell Angular where to look for them.

Next, you also need to install jQuery using the following command:

 $ npm install --save jquery

At the time of this tutorial jquery v3.4.1 will be installed.

Step 3 (Method 1) - Adding Bootstrap 4 to Angular 9 Using angular.json

Open the angular.json file of your project and include:

  • node_modules/bootstrap/dist/css/bootstrap.css in the projects->architect->build->styles array,
  • node_modules/bootstrap/dist/js/bootstrap.js in the projects->architect->build->scripts array,
  • node_modules/bootstrap/dist/js/bootstrap.js in the projects->architect->build->scripts array,

As follows:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1, 
  "newProjectRoot": "projects",
  "projects": {
    "angular-bootstrap-examples": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/angular-bootstrap-examples",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/bootstrap/dist/css/bootstrap.css",
              "src/styles.css"              
            ],
            "scripts": [
              "./node_modules/jquery/dist/jquery.js",
              "./node_modules/bootstrap/dist/js/bootstrap.js"
            ]
          },

Note: You also need to add the jQuery JavaScript library file.

Step 3 (Method 2) - Adding Bootstrap 4 to Angular 9 Using index.html

You can also include Bootstrap files from node_modules/bootstrap using the index.html file.

Open the src/index.html file and add the following:

  • A <link> tag for adding the bootstrap.css file in the <head> section,
  • A <script> tag for adding the jquery.js file before the closing </body> tag,
  • A <script> tag for adding the bootstrap.js file before the </body> tag.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular Bootstrap 4 Examples</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">

</head>
<body>
  <app-root></app-root>
  <script src="../node_modules/jquery/dist/jquery.js"></script>
  <script src="../node_modules/bootstrap/dist/js/bootstrap.js"></script>    
</body>
</html>

Step 3 (Method 3) - Adding Bootstrap 4 to Angular 9 Using styles.css

We can also use the styles.css file to add the CSS file of Bootstrap to our project.

Open the src/styles.css file of your Angular project and import the bootstrap.css file as follows:

@import "~bootstrap/dist/css/bootstrap.css"

This replaces the previous method(s) so you don't need to add the file to the styles array of the angular.json file or to the index.html file.

Note: The JS file(s) can be added using the scripts array or the <script> tag as the previous methods.

Alternative Step - Adding Bootstrap 4 Using ng-bootstrap and ngx-bootstrap

Bootstrap depends on jQuery and Popper.js libraries, and if you don't include them in your project, any Bootstrap components that rely on JavaScript will not work.

Why not include those libs? For Angular it's better to avoid using libraries that make direct manipulation of the DOM (like jQuery) and let Angular handle that.

Now what if you need the complete features of Bootstrap 4 without the JS libraries?

A better way is to use component libraries created for the sake of making Bootstrap work seamlessly with Angular such as ng-bootstrap or ngx-bootstrap

So first you'll need to install the library from npm using the following command:

npm install --save @ng-bootstrap/ng-bootstrap

Once you finish the installation you'll need to import the main module.

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

Next you'll need to add the module you imported in your app root module

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [/*...*/],
  imports: [/*...*/, NgbModule.forRoot()],
  /*...*/
})
export class AppModule {
}

Please note that ng-bootstrap requires the Bootstrap 4 CSS file to be present.

You can add it in the styles array of the angular.json file like that:

"styles": [
  "styles.css",
  "../node_modules/bootstrap/dist/css/bootstrap.css"
],

Now you can use Bootstrap 4 in your Angular application.

You can find all the available components via this link.

You can also use the ngx-bootstrap library

Simply head back to your terminal, make sure you are inside your Angular project then run the following command to install ngx-bootstrap

npm install ngx-bootstrap --save

You also need the Bootstrap 4 CSS files. Add the following line in the <head> of your Angular app which includes Bootstrap from a CDN

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">

You can also install bootstrap from npm and use the previous way to include the CSS file (via the styles array in the angular-cli.json file)

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

Next open src/app/app.module.ts and add

import { BsDropdownModule} from 'ngx-bootstrap/dropdown';
import { AlertModule } from 'ngx-bootstrap';

/*...*/

@NgModule({
   /*...*/
   imports: [BsDropdownModule.forRoot(),AlertModule.forRoot(), /*...*/ ],
    /*...*/ 
})

This an example of importing two components BsDropdownModule and AlertModule.

You need to import the module for each component you want to use in the same way.

ngx-bootstrap provides each BS component in each own module so you only import the components you need. In this way your app will be smaller since it bundles only the components you are actually using.

You can find all the available components that you can use from the docs

Adding Bootstrap 4 to Angular 9

Thanks to the new ng add command added on Angular 7+, you have a new simpler and easier way to add Bootstrap without using the npm install command for installing the required dependencies or adding any configurations.

You can simply run the following command to add ng-bootstrap:

$ ng add @ng-bootstrap/schematics

That's it. You now have support for Bootstrap components and styles without any extra configurations. You also don't need jQuery since we are using ng-bootstrap.

Conclusion

In this article, we've seen different ways of including Bootstrap 4 in Angular 9 apps:

  • Using original Bootstrap 4 assets from npm,
  • Using the ng-bootstrap library,
  • And finally using the ngx-bootstrap

The most important difference between ng-bootstrap vs. ngx-bootstrapis that ngx-bootstrap uses separate modules for components to reduce the final app size.

How to CSS Centering for Angular

How to CSS Centering for Angular

Centering elements in CSS either horizontally or vertically was always tricky and developers have used many methods which sometimes didn't even make sense particularly for beginners. But with the advent of Flexbox, CSS centering became easier and clearer than ever.

In this tutorial, we'll learn how to center elements in CSS and Angular 8 using the modern Flexbox layout.

Centering elements in CSS either horizontally or vertically was always tricky and developers have used many methods which sometimes didn't even make sense particularly for beginners.

But with the advent of Flexbox, CSS centering became easier and clearer than ever.

We'll make use of Stackblitz for our Angular project.

Horizontal Centering

Let's start with horizontal centering. Open the src/app/app.component.html file and add the following <div>:

<div class="center">
  <h1>Hello Angular 8!</h1>
</div>

We add a div with a center class. Inside it, we add an <h1> tag.

Next, open the src/app/app.component.css file and add the center class with the following styles:

.center {
  display: flex;
  justify-content: center;
}

That's it. our content is horizontally centered by simply making the div a flex container and using the justify-content property. Here is a screenshot:

Vertical Centering

Now, let's see how we can center the content vertically using Flexbox.

It's also easy to achieve that using Flexbox by simply adding align-items: center.

Let's first add the following styles to change the color and height of the containing div so we can see the content clearly centered vertically:

.center {
  display: flex;
  height: 300px;
  background-color: #ff1124;
  justify-content: center;
}

This is the result:

Now, let's apply the vertical centering:

.center {
  display: flex;
  height: 300px;
  background-color: #ff1124;
  justify-content: center;
  align-items: center;
}

This is the result:

This will center any elements inside the div. If you would like to center specific elements, you can use align-self: center, instead, on the element.

.center {
  display: flex;
  height: 300px;
  background-color: #ff1124;
  justify-content: center;
}

.center h1{
align-self: center;
}

If you need to center on the whole page, you can simply give the div the same height as the page:

.center {
display: flex;
background-color: #ff1124;
justify-content: center;
height: 100vh;
}

.center h1{
align-self: center;
}

This is a screenshot:

Conclusion

In this quick example, we've seen how we can center elements in CSS horizontally and vertically using Flexblox which provides easy and clear ways to achieve that without resorting to old CSS tricks.

This example was demonstrated with an Angular 8 project but these tricks are not tied to Angular in any way.

I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others

Further reading

‚ė쬆What‚Äôs New in Angular 8.0

‚ė쬆Angular 8 is coming

‚ė쬆Angular 8 Tutorial - User Registration and Login Example

‚ė쬆Angular 8 HttpClient & Http Tutorial ‚Äď Build and Consume RESTful API

‚ė쬆Understanding Angular 8's Differential Loading

‚ė쬆Angular & NodeJS - The MEAN Stack Guide

‚ė쬆Angular 8 + Spring Boot 2.2: Build a CRUD App Today!

‚ė쬆 Angular 8 Node & Express JS File Upload

‚ė쬆Angular Authentication Tutorial for Beginners


Originally published on techiediaries.com

Using CSS Grid Layout in Angular project

Using CSS Grid Layout in Angular project

This CSS Grid layout tutorial is designed for Angular 7/8 developers that want to learn how to build responsive layouts with modern CSS.

This CSS Grid layout tutorial is designed for Angular 7/8 developers that want to learn how to build responsive layouts with modern CSS. We'll first start with a general introduction to learn about the basic concepts and then we'll see how to use it within an Angular 7/8 app to create the famous holy grail layout.

In this tutorial, we’ll teach you how to use CSS Grid layout to easily build interfaces and responsive HTML layouts without resorting to using the old and complex CSS tricks for achieving the same results but instead using clean and easy to maintain CSS styles.

Grid layouts are common in the design of websites and web apps, and thanks to the CSS Grid layout in modern web browsers, we now have an easy way for creating these layouts.

CSS Grid layout is now supported in the major browsers such as Safari, Chrome, Firefox, and Edge so developers can start using it with more confidence and may also use fallbacks for older browsers.

In this first part of our tutorial, we’ll go through the basic concepts of CSS Grid before we build our Angular UI with it.

With CSS Grid layout:

  • You‚Äôll be able to easily create two-dimensional layouts without using complex CSS tricks and HTML tables,
  • You can create layouts with simple HTML markup,
  • You don‚Äôt need to use CSS frameworks like Bootstrap.

In this CSS Grid tutorial, you'll learn:

  • What is a grid container and how to create it,
  • What is an implicit and explicit grid,
  • What're grid tracks and how to use them,
  • What're grid gaps or gutters,
  • How to position items using grid line numbers,
  • How to span items across rows and columns,
  • How to name grid lines,
  • How to positioning items by line names,
  • How to name and position items by grid areas, etc.

In a CSS Grid layout, you’ll have two main things, the container grid, and the items. For example:

<div style="display: grid;">
  <div style="background: #00112211;">1</div>
  <div style="background: #00112233;">2</div>
  <div style="background: #00112288;">3</div>
  <div style="background: #00112299;">4</div>
  <div style="background: #001122dd;">5</div>
</div>

By setting the CSS display property to grid, we turn the outer div into a grid container.

Note: You can create a grid container by simply applying the CSS display property to an HTML element like a <div> and gives it a value of grid or inline-grid.

Since we didn’t apply any other properties, we’ll have a default grid that displays the items in rows similar to a vertical stack. Each item takes the full available width.

Note: The Grid items are simply the top-level children of the grid container.

This is a screenshot of our grid:

If you change the display property to inline-grid, items will not span the full available width:

We can see this layout as a one-dimensional grid with one column and 5 rows. But, CSS Grid allows us to create two-dimensional grids with multiple rows and columns.

CSS Grid's columns and rows

A CSS grid can have multiple columns and rows. We can use the grid-template-row and grid-template-column properties to control the layout of the grid by defining the number of columns of rows and their size.

We can update the previous grid without changing anything in the HTML markup but CSS. But, first, since we’ll need to add more CSS, let’s pull the inline styles into a separate CSS class.

This is the HTML markup:

<div class = "grid">
  <div class="item" style="background: #00112211;">1</div>
  <div class="item" style="background: #00112233;">2</div>
  <div class="item" style="background: #00112288;">3</div>
  <div class="item" style="background: #00112299;">4</div>
  <div class="item" style="background: #001122aa;">5</div>
</div>

The outer div has a grid class and each inner div has an item class. It’s up to you to choose the name of your classes and you can pick any names you see convenient.

Let's see how to use the grid-template-rows property to create row tracks:

.grid {
  display: grid;
  grid-template-rows: 20px 20px 40px 20px 40px;
}

We created a row track for each item by specifying a value in pixel (that represents the height of the row) in grid-template-rows template. You can also use other units like % or em, etc.

Just like rows, you can create column tracks by specifying values in the grid-template-columns template.

.grid {
  display: grid;
  grid-template-rows:    20px 20px 40px 20px 40px;
  grid-template-columns: 100px;  
}

We have created one column track with a witdh of 100px:

If you want the column to take all the available width in the container, you can use the fraction unit denoted by fr:

.grid {
  display: grid;
  grid-template-rows:    20px 20px 40px 20px 40px;
  grid-template-columns: 1fr;
}

We've our previous grid:

![](

Now, let's change our markup as follows:

    <div class = "grid">
      <div class="item" style="background: #00112211;">1:1</div>
      <div class="item" style="background: #00112233;">1:2</div>
      <div class="item" style="background: #00112288;">1:3</div>
      <div class="item" style="background: #00112299;">2:1</div>
      <div class="item" style="background: #001122aa;">2:2</div>
    </div>

Next, change CSS grid as follows:

    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-template-rows:    1fr 1fr 1fr;
    }

The grid-template-columns and grid-template-rows properties allow us to create a template for making our grid. If you look at this part of the code:

  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows:    1fr 1fr 1fr;

You’ll be able to depict that we have a grid, each one 1fr unit makes a cell. We can also see it as a 3x3 matrix (3 rows and 3 columns) if you are familiar with this concept in Mathematics. Each cell in the matrix contains how much space the cell takes in the grid layout. We use the fr unit.

With the CSS Grid Layout, we have a new fr unit which stands for* fractional unit:

  • 1fr¬†means 1 part of the available space,
  • 2fr¬†means 2 parts of the available space, etc.

How the space of each cell is calculated?

In our example, we have three columns and each column equally takes 1fr which means each column takes 1/3 of the available space.

We also have three rows and each row takes 1fr which means each row takes 1/3 of the available space.

This is exactly how our grid layout will look like when rendered in HTML except that we don’t have items to fill the sixth cell at the 2:3 position and the last row:

We can identify each cell by its row and column numbers in the row: column format.

By default, each <div> item has been given a position in the grid starting from left. The topmost element is positioned at cell 1:1 but you can also change the default positions.

CSS Grid gaps (Gutters)

You can add space between the grid items using the grid-column-gap and grid-row-gap properties which create gutters between columns and rows.

.grid {
  display: grid;
  grid-template-rows:    1fr 1fr 1fr;
  grid-template-columns: 1fr 1fr 1fr;
  grid-row-gap:    10px;
  grid-column-gap: 10px;  
}

Note: You can also use grid-gap as a shorthand for grid-row-gap and grid-column-gap. For example: grid-gap: 10px 10px;.
Positioning items in CSS Grid Layout

CSS Grid Layout allows you to control the position and size of each cell individually using the following properties:

  • grid-column-start,
  • grid-column-end,
  • grid-row-start,
  • grid-row-end.

Or also their shorthands, grid-column and grid-row.

Let's see this with example. Let's apply the following styles to the first item:

div:nth-child(1) {
  grid-column-start: 2;
  grid-column-end: 3; 
}

This will position the first item in the second column instead of the first column and will also cause all the other items to shift by one column:

Spanning items in CSS Grid Layout

Grid items span only one column and row tracks by default but can span multiple row and/or column tracks using the same grid-row-* and grid-column-* by simply setting the end position to a line which is more than one row or column away from the start.

For example, let's make the first item span the first two columns by adding the following styles:

div:nth-child(1) {
  grid-column-start: 1;
  grid-column-end: 3; 
}

Let's also span the first item in across the first two rows and the last item across the two last rows:

div:nth-child(1) {
  grid-column-start: 1;
  grid-column-end: 3; 

grid-row-start: 1;
grid-row-end: 3;
}

div:nth-child(5) {
grid-row-start: 2;
grid-row-end: 4;
}

This is our grid at this point of this tutorial:

.grid {
display: grid;
grid-template-rows: 1fr 1fr 1fr;
grid-template-columns: 1fr 1fr 1fr;

grid-row-gap: 1px;
grid-column-gap: 1px;
}

div:nth-child(1) {
grid-column-start: 1;
grid-column-end: 3;
}

div:nth-child(3) {
grid-column-start: 1;
grid-column-end: 3;
}

div:nth-child(5) {
grid-column-start: 1;
grid-column-end: 4;
}

CSS Grid Areas

CSS Grid layout has other features like areas which give more flexebility when building layouts. We can give each cell of the grid a name as follows:

.grid {
display: grid;
grid-template-rows: 1fr 1fr 1fr;
grid-template-columns: 1fr 1fr 1fr;

grid-template-areas: "header header header"
"content content sidebar"
"footer footer footer";

grid-row-gap: 1px;
grid-column-gap: 1px;
}

Next, we can position the items inside the grid using area names and the grid-area property as follows:

div:nth-child(1) {
grid-area: header
}

div:nth-child(2) {
grid-area: content
}

div:nth-child(3) {
grid-area: sidebar
}

div:nth-child(4) {
grid-area: footer;
width: 50%;
justify-self: start
}
div:nth-child(5) {
grid-area: footer;
width: 50%;
justify-self: end
}

The fourth and fifth items are both assigned to the footer area so we need to adjust their widths and then use alignment properties like justify-self to divide the footer space between the two items:

After seeing the fundamental concepts of CSS Grid Layout, let's now create the famous holy grail layout with Angular 8.

Prerequisites

Let's get started with the prerequisites of this tutorial. You need to have:

  • Node 8.9+, and NPM 5.5.1+ installed on your development machine,
  • Working knowledge of TypeScript and Angular,
  • Angular CLI installed on your system. At the time of writing this tutorial,¬†angular/cli v8.3.2¬†is available.

You can install Angular CLI using the following command:

$ npm install -g @angular/cli
Creating an Angular 8 project

Let's now create an Angular 8 project. Open a new terminal and run the following command:

$ ng new angular-cssgrid-demo

You'll be prompted if you Would you like to add Angular routing? Type y for Yes and Which stylesheet format would you like to use? Choose the first option which is CSS.

Next, go to your project’s folder and run the following commands to start the development server:

$ cd angular-cssgrid-demo
$ ng serve

Using your web browser, you can visit your app at the http://localhost:4200/ address:

Before proceeding to build our CSS Grid layout example, let's first clean our project from the placeholder code. Head to the src/app/app.component.html and remove the placeholder from the file. This is the content of the file at this point of the tutorial:

 <router-outlet></router-outlet>
Creating the components

The holy grail layout is a web design pattern that is commonly used in websites. The website UI is divided into;

  • A header,
  • A navigation bar,
  • Main content on the middle,
  • A footer.

Components are the basic building blocks of Angular apps. In our application, we can compose the UI using the following parts:

  • Header, navbar and footer components,
  • Home and about pages.

The home and about pages are also components but they are connected to specific routes, so users can navigate between them and the Angular router will take care of inserting the appropriate component in the router-outlet when the corresponding route is triggered.

While, the header, navbar and footer components are common (reusable) parts between all the pages of the application so they need to belong to the app shell in the src/app/app.component.html file.

Let's proceed to create the components. Open a new terminal and run the following commands:

$ ng generate component home
$ ng generate component about
$ ng generate component header
$ ng generate component navbar
$ ng generate component footer

For example, for the header component, we'll have the following files:

  • src/app/header/header.component.html,
  • src/app/header/header.component.spec.ts,
  • src/app/header/header.component.ts,
  • src/app/header/header.component.css.

Components will be automatically added by the CLI to the main application module in the src/app/app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HeaderComponent } from './header/header.component';
import { NavbarComponent } from './navbar/navbar.component';
import { FooterComponent } from './footer/footer.component';

@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
HeaderComponent,
NavbarComponent,
FooterComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Let's now add the home and about components to the router configuration in the routing module that was generated by the CLI when we created our project. Open the src/app/app-routing.module.ts file and update as follows:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full'},
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
];

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

Next, we need to add the header, navbar and footer components to the app shell. Open the src/app/app.component.html file and update it as follows:

<app-header></app-header>
<app-navbar></app-navbar>
<router-outlet></router-outlet>
<app-footer></app-footer>

You can find the selector to reference the component from the templates of the other components from the selector attribute of the meta-information object passed to the component decorator. For example, for the header component, the selector attribute has the app-header value:

import { Component, OnInit } from '@angular/core';

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

constructor() { }

ngOnInit() {
}

}

If you save your changes, your app will be live-reloaded and you should be redirected to the home page and see the following interface:

The header, navbar and footer content will be common between the home and about pages.

Now, let's add some placeholder content to our components and pages. Open the src/app/home/home.components.html file and add the following markup:

<h2>Home</h2>

<p>This demo is making use of CSS Grid layout for creating the layout.</p>
<p> Go to the src/app/app.component.css file for the CSS code of this layout.</p>

Next, open the src/app/about/about.components.html file and add the following markup:

<h2>About us</h2>
<p>This is the about page of our application.</p>

Next, open the src/app/navbar/navbar.components.html file and add the following markup;

<a  [routerLink]="['/home']">HOME</a>
<a [routerLink]="['/about']">ABOUT US</a>

Next, open the src/app/header/header.component.html file and add the following markup;

<header>
<h1>Angular App</h1>
</header>

Next, open the src/app/footer/footer.component.html file and add the following markup;

<footer>
<span>
Copyright 2019
</span>
</footer>

Open the src/app/app.component.css file and add the following styles:

app-root {
height: 100%;
width: 100%;

display: grid;
grid-template-columns: 1fr;
grid-template-rows: 100px max-content 1fr max-content;
grid-template-areas:
  "header"
  "navbar"
  "main"
  "footer";

}

app-header {
grid-area: header;
}

app-navbar {
grid-area: navbar;
}

router-outlet + * {
grid-area: main;
}

app-footer {
grid-area: footer;
}

Open the src/app/header/header.component.css and add the following CSS code:

:host {
background: #9154f3;
color: whitesmoke;

border-top: 0px solid #9154f3;
font-size: 21px;
font-weight: 500;
line-height: 49px;
border-bottom-width: 1px;
padding: 0 17px;

}

Open the src/app/footer/footer.component.css and add the following CSS code :

:host {
background: #9154f3;
color: whitesmoke;
border-top: 1px solid #9154f3;
padding: 9px 16px;
box-sizing: border-box;
}

Next, open the src/app/navbar/navbar.component.css and add the following CSS code :

:host {
border: 0 solid #e1e1e1;
border-bottom-width: 1px;
height: 49px;
padding: 0 16px;

display: flex;
flex-flow: row;
align-items: center;

}

a {
color: #c697d8;
font-size: 19px;
font-weight: 900;
line-height: 49px;
margin-right: 27px;
text-decoration: none;
}

Next, open the src/app/home/home.component.css and src/app/about/about.component.css files and add the following CSS code:

:host {
padding: 3px 19px;
}

At this point, we would expect to get the correct layout but this is not actually what happens:

![}(https://www.diigo.com/file/image/rscqpoqzocbpdrbeozdsdrssdr/Angulardemo.jpg)

To solve this we need to apply ViewEncapsulation.None to the App component. Open the src/app/app.component.ts file and update as follows:

import { Component, ViewEncapsulation } from '@angular/core';

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

This is a screenshot of our holy grail Angular UI:

Conclusion

In this tutorial, we've introduced CSS Grid layout to Angular developers and seen the fundamental concepts of how to create modern layouts using it. I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

Thanks For Visiting, Keep Visiting.

Originally published on techiediaries.com