How to create a custom Component in Angular 7?

How to create a custom Component in Angular 7?

Angular Components can be understood like LEGO pieces. Angular components can be used multiple times, once they are created. An angular app is a structure build of all those component which we have created in a similar way we make a Lego Structure from little Lego pieces. So this is what and Angular Component is, but this article includes much more other than this. So without wasting any further time, let’s get started.

Creating a custom angular component in Angular 7 can be tricky sometimes due to the modularity and complexity involved. But it is far easy as complex it appears to be. Given below are the steps and information after which you will get to know that how can we create a custom component in angular.

What are the tasks of a component?

The main task of a component in angular is to display a specific page/section and its data with the support of Interpolation, Directives, and Pipes. Other than this, angular component can also be used for binding data between the view and the model.

What is inside of a component?

An Angular component mainly consists of 3 parts which are as follows:

  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). One thing to note of is that We should carefully name our Folders when creating an Angular App, otherwise, we get lost inside a bigger project.

How does a component work?

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

@Component ({
selector :’app-root’,
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, like an HTML tag. TemplateUrl is where the HTML View of the component is. The 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.

Leave a Comment