How to create a custom Component in Angular 7?

We can think of Angular Components like LEGO pieces. We create a component once but can use them multiple times in different parts of our website.

An Angular app is a tree structure consisting of all those components that we create, like how we make a Lego Structure from little Lego pieces.

So this is basically what an Angular Component is, but that’s not all. In this article, you will find answers to the following questions:

- What are the tasks of a component?- What is inside of a component?- How does a component work?- What is ngOnInit?

The main tasks of a component are:

1. Displaying a specific page/section and its data with the support of Interpolation, Directives, and Pipes
2. Binding data between the view and the model.

What is inside of a component?
A component contains (mostly) 3 parts:

 1. Template File— HTML View 2. TypeScript File — Model 3. Style File — CSS

The Folder (app) is our Component Folder, which contains HTML, CSS and TS files. Spec.ts is for testing, and you can ignore module.ts for now.
So each component has its own HTML structure, style (CSS) and functionality (TS).

But how does a component work actually?
We should carefully name our Folders when creating an Angular App, otherwise, we get lost inside a bigger project.

How does a component work?
Inside the app.component.ts:

import {Component} from ‘@angular/core’;

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

We have here an ordinary TypeScript class. But in order to use it as a component:
First of all, we import Component from the @ angular/core library, so we can create an Angular Component
The @ Component decorator marks the TS class as a Component and allows us to add the following metadata
The selector is for calling the component inside other HTML files of the project, as an HTML tag:
TemplateUrl is where the HTML View of the component is.
style URLs (can be more than 1) is where the style CSS of the component is.
Finally, we export the class(component) so that we can call it inside the app.module or other places in the project.

Now let’s see how to use it…
After creating the component, we must save it inside the App Module.

By in on Jan 07 2020
• Jan, 2020 13

What is a component?
Every Angular application has at least one component that is used to display the data on the View.
The component contains metadata like animation effect, style to apply the components, template, input-output, import etc.
These are the main building blocks of an Angular application.
When we create any component, it gets defined in NgModule.
Suppose you are going to develop a simple application which contains home page, logo - menu list - footer etc.; the blogs page contains blogs list, contact information about the author etc. So we are going to create these components.

• 1