Create a Component in Angular 4

In this article are will learn how to create a component, how to create a component within a component and how to use the component in angular 4 Application.

The Angular CLI has something that we call generators that let you generate components, routes, services and pipes with a simple command in the application for you. For instance, you can use the following command to create a component

How to create a component in Angular 4?

ng generate component header

here ng generate is a command through which we are generating a component named header.

if you want to create a component within a folder then you can create using below-mentioned command

ng generate component components/header

There is also a shorthand version of the above command.

ng g c components/header

both command will act as a same.

here ng generate will create a component header within a components folder. Here “components” folder is not necessary but it is good to put the related components in a folder. So that you will have a nice project structure.

angular4 component

 

This is the expected output you will get when you run the above command.

Now how to use the component which we have just created.

Now you can put HTML related code in header.component.html file and the logic part will be in header.component.ts and if you have CSS related that component only you can put in header.component.css.

So we have created a component called header. Now we will create a component called footer and will put it in the same folder called components.

ng g c components/footer

To run you angular app run the command ng serve. Open your browser and run http://localhost:4200/.

angular default page

Now, let’s use our created component in our application.

So open app.module.ts. Now you can see header and footer component files are already declared in app.module.ts as you can see below:-

import { BrowserModule } from ‘@angular/platform-browser’;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component';
 
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Now open src\app\app.component.html. And add <app-header></app-header> and <app-footer></app-footer>

So to add component in view file you need to put app- before component name. try to make you index page like the image as below:

 

header-footer component

 

Understand Angular 4 Application Terminologies

What is Bootstrapping?

In Angular 4 we use a bootstrapper. You can find the bootstrapping logic in the src/main.ts module:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));

Which starts your application by loading important modules and by defining environment level logic.

What is a Module?

A TypeScript module is a way to encapsulate, group, reuse, distribute and load code in JavaScript.

Generally, a module will contain code that encapsulates a specific functionality. The module will expose this functionality to the rest of the application by defining a series of exports that other parts of the system can then import.

The core module for Angular 4, for instance, is called ‘angular2/core’ and it gives you access to Angular core primitives like Component.

In the above code, we are importing the platformBrowserDynamic object from ‘@angular/platform-browser-dynamic’ module and called its bootstrapModule function with the AppModule as an argument.

Some things we need to note here are:

  • The ‘@angular/platform-browser-dynamic bootstrapper tells us that Angular 4 is platform agnostic. That is, you can run it in the browser, but you can also run it on a web worker or in the server using different bootstrappers.
  • Notice how we import modules in a different way, Angular 2 modules are imported by name, and application components are imported using relative paths.

Calling the bootstrapModule function with the AppModule as argument tells Angular that this module is the main module for your application.

Angular 2 Modules

Angular 2 modules and the new NgModule decorator allow us to declare in one place all the dependencies and components of our application without the need to do it on a per-component basis. a higher level module to wrap ES6 modules that are all about developer ergonomics.

Angular 2 module code

The NgModule decorator takes an object with the following information:

  • The imports array where you declare your module dependencies, for instance, browser, forms, routing or http. The BrowserModule we are using above contains all the dependencies necessary to run Angular 4 on a browser.
  • The declaration array where you declare the components and directives that belong to the current module.
  • And A bootstrap array that identifies our root component that Angular 4 uses to bootstrap your application.

In this example, we import an AppComponent component from the app.component.ts module and set it as the root of our application.

What is a Component?

The component is the core building block of Angular 4 applications. It represents a reusable piece of UI that is usually depicted by a custom HTML element tag.

A component is self-contained and is constituted by :

  • A piece of HTML code that is known as Template.
  • A class that encapsulates the data and access to these data are available to the Template.
  • And the Selector – CSS selector that identifies our component in a Template.

The AppComponent looks like this:

Angular Tutorials : Angular component

This code is available on your project, which will be located at my-app/src/app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = "app";
}

This code has an AppComponent class that is decorated by some metadata in the form a TypeScript decorator @Component which binds the class to its template, its styles and the app-root selector (Can you remember the <app-root> element from the index.html file?).

This metadata tells Angular 4 that whenever you see a <app-root> HTML element you should render the template in templateUrl, with the styles in stylesUrls and in the context of the AppComponent class.

What is a Decorator?

Think of a decorator like a function that is applied to whatever it decorates. In this case, the Component decorator attaches some metadata to the AppComponent class.

If you open component.html file you`ll see title variable in a h1 tag among other things, which will look something like this

  <h1>
    Welcome to {{ title }}!
  </h1>

The double brackets around title  (which we call interpolation syntax) tells Angular 4 to display the content of the component title variable when rendering the component. Indeed, if you run ng serve you can see how the browser renders the text “app” inside an h1 element.

Now look back at the AppComponent definition and the project structure you’ll realize that the Angular CLI follows a convention when creating components:

  • All files for a given component are placed within the same folder named like the component itself (in this case app)
  • These files have been named with component and have different extensions based on their function:
    • component.ts for the component itself
    • component.html for the template
    • component.scss for the styles

Now let’s see how we can bind the AppComponent class members to the template. Let’s change the title property value from “app” to “My First Angular App”. If you now save the file, your browser should automatically refresh itself and you should be able to see the My First Angular App as the title of your app (If you closed your browser just open it again and if you stopped the development server then remember to run ng serve –open to start it again and see your changes).

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = "My First Angular App";
}

For More read our Next Articles

Create Your First Angular 4 Application

Welcome!! Fellow Angular 4 aspirant, I have written this tutorial in hope of helping audacious people like yourselves who want to create their first angular 4  application with Windows OS on their own. So without wasting further time, let’s begin with this article.

Basic Dependencies

Before we can begin, we need to ensure you have a few dependencies installed. Which are necessary for this tutorial

  • Node.js with NPM (Node Package Manager)
  • Angular-CLI (Command Line Interface)

To check whether or not you have Node.js installed, visit your  command line and type: node -v

Angular 4 Tutorial : check node version through command prompt

 

If the command was not recognized by your system, you need to install Node.js.

  1. Visit the NodeJs download page and choose download package based on your OS.
  2. Accept the terms and agreement condition, choose an installation folder, and hit Next on the Custom Setup page. By default, it will install the npm package manager which we will need.
  3. Now again open your command line and type node –v . It will show you the currently installed node.js version

Next, we are going to install the Angular-CLI.

At the console, type:

npm install -g @angular/cli

Once finished, type:

>ng –v

The resulting output will look something like this:

Angular 4 Tutorial:Output After Angular-cli successfully installed in your system
Output After Angular-cli successfully installed in your system

When we run ng -v while inside an Angular project folder, it will also provide us with which version of Angular that particular project is using.

Why Angular CLI ?

The CLI helps us by automating away many of the cumbersome tasks by managing configuration along with providing best practices that have been discovered by the community over the time, and by helping you to build more maintainable code, the CLI exposes some of the most powerful capabilities of Angular in a way that is easier to get started, and easier to get moving quickly when compared to rolling everything together yourself.

Now you are all set to create your own project using Angular CLI. The command that we use to access the Angular CLI is ng. To create a new app type the following:

ng new my-app

Angular 4 tutorials: ng new project-name
ng new [project-name]

This will create a new Angular 4 project from scratch and set it up so that you can use SASS as CSS preprocessor. If you go inside the my-app folder that should have just been created you’ll find a folder structure that will look more or less like this:

- src
|
|-- app                 # your app source code
|-- assets              # static files like images,videos etc
|-- index.html          # entry point to your app
|-- styles.scss         # the global styles for your app
|-- environments        # here you can define different environment configuration (prod, dev, etc)
|-- node_modules        # the source code of your app's dependencies
|-- package.json        # the manifest of your app that states all dependencies
|-- tsconfig.json       # TypeScript compiler configuration
|-- tslint.json         # TypeScript linting configuration
|-- e2e                 # a folder with end to end tests
|--karma.conf.js        # karma test runner configuration
|--protractor.conf.js   # protractor e2e tests configuration
|--.gitignore
|--README.md

Type the following command in your command prompt:

c:\my-app> ng serve –open

Angular 4 Tutorial : Run your angular app

 

This will start the development server, open up a default browser and load your app.

Congratulation you have successfully setup your first angular 4 application!

 

Know you Angular 4 project in detail

What is SASS?

Sass is an extension of CSS that adds power and elegance to the basic CSS on its own, As CSS stylesheets are getting larger, more complex, and harder to maintain in these days. This is where a preprocessor like SASS can help. Sass provides us with features that don’t exist in CSS yet like variables, nesting, mixins, inheritance and other nifty goodies that make writing CSS fun again and efficient to use.

What is Index.html?

The index.html is the entry point to our application:

  • It links to styles and javascript files
  • It provides the HTML markup for our application with custom <app-root> tag. This is root node of our Angular Application.

If you open your project index.html file. You’ll see the code like in below image:

Angular Tutorial: Index.html
index.html

You might have noticed that styles and javascript files are missing. All we can see is a custom element app-root tag. The reason for that is the Angular CLI relies on Webpack to inject these files when they are needed.

What is Webpack?

Webpack is a module bundler that takes all these files and modules, processes them and makes them available so that they can be run in any browser. Moreover, it can optimize your application by taking advantage of a rich community of plugins.

Take a look at the awesome Webpack docs if you want to learn more about it.

For More read our Next Articles