How to Create & Use Component in Angular 16 App

Last Updated on by in Angular
What makes Angular component so significant in the development process with Angular.Well, the major part of the development relies on components. In simpler terms, components are nothing but classes that interact with the front end, a.k.a. the .html files.

Now, it’s time for us to take a look at the file structure below.

It is made of the following files –

  • app.component.css
  • app.component.html
  • app.component.spec.ts
  • app.component.ts
  • app.module.ts

When you create a new project with the help of Angular CLI command, the aforementioned files are automatically generated. When you open up the app.module.ts file, you will come across few imported libraries.

You will also come across a declarative which responds to app component as follows –

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

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

The AppComponent variable belongs to the declarations and it has already been imported. It is assigned as the parent component.

If you wish to create components on your own, you can use Angular CLI command. But you must remember that App Component will remain as the parent component, no matter what.

The components you create will be identified as child components.

It’s time for us to create the new component with the help of commands.

ng g component new-component

You will get the following output when you run the aforementioned command in the command line –

ng g component new-component

# CREATE src/app/new-component/new-component.component.css (0 bytes)
# CREATE src/app/new-component/new-component.component.html (32 bytes)
# CREATE src/app/new-component/new-component.component.spec.ts (671 bytes)
# CREATE src/app/new-component/new-component.component.ts (296 bytes)
# UPDATE src/app/app.module.ts (422 bytes)

If you wish to know where the new folder is created, you can check the file structure.

As for the new component new folder, you may check under the src/app folder.

Inspect the new component folder.

When you inspect the new component folder, you will be greeted by the following files –

  • new-component.component.css – The required CSS file is created for the new component.
  • new-component.component.html – HTML file has been created.
  • new-component.component.spec.ts – we shall be using this for unit testing.
  • new-component.component.ts – You will be able to define the properties, module etc. with the help of this.
  • The new-component.component.ts file will be created as follows –

The app.module.ts file changes will be added as follows –

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

import { AppComponent } from './app.component';

// Automatically imported component by Angular CLI
import { NewComponentComponent } from './new-component/new-component.component';

@NgModule({
  declarations: [
    AppComponent,
    NewComponentComponent // Component declared by Angular CLI
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

When you inspect the new-component.component.ts file, you will come across a new class named NewComponentComponent. This class is responsible for implementing OnInit.

which has a method and constructor and a lifecycle hook named ngOnInit(). Whenever you execute this class, ngOnInit will be called as soon as the NewComponentComponent class is ready.

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

@Component({
  selector: 'app-new-component',                   
  templateUrl: './new-component.component.html',  // Manages Component's HTML
  styleUrls: ['./new-component.component.scss']    // Handles Component's styling
})
export class NewComponentComponent implements OnInit {

  constructor() { }   // Used to inject dependencies

  ngOnInit() {  // Lifecycle hook, initialize when component class is ready
  }

}

How the Angular app flow funcitons?

Now we will see how the flow functions, ass we have stated before, the app component assumes the role of the parent component.

Components added thereafter become child components.Index.html will be first executed when you visit the URL http://localhost:4200. We have demonstrated it below.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularTest</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
  <app-root></app-root>
</body>

</html>

What we see above is the regular HTML file. Things printed there will not be visible on the browser. Take a closer look at the body section and the tag there.

<app-root></app-root>

Angular is responsible for the root tag you see there. It was created by default. You will find reference to it in the main.ts file.

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));

Where does AppModule come from?

We have imported it from the main parent module app. And it is passed onto the bootstrap module as well. It’s time for us to check out the app.module.ts file –

It’s interesting to the naming of AppComponent. It is pretty clear that it is used as a variable to contain app references.

Let’s now check out the app.components.ts file.

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

import { AppComponent } from './app.component';
import { NewComponentComponent } from './new-component/new-component.component';

@NgModule({
  declarations: [
    AppComponent,
    NewComponentComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We have imported Angular core. We are referring it as the Component and it is used in the Decorator as –

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

In the reference of declaratory to the selector, styleUrl and templateUrl are given. As for selector, it is just a tag which we have included in the index.html file we have already seen above.

A title is the variable of the class AppComponent. This variable is accessed by the browser to show the title.

The @Component utilizes the templateUrl named app.component.html.

Refer the code below.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
}

As you can see, it only has HTML code in it. The variable title is appended in curly brackets. The browser accesses the value of title from the app.component.ts file and replaces the variable with the value. This process is referred to as binding. We are going to see more of binding in the upcoming tutorials.

We have successfully created a new component named new component. And it finds a place in the app.modules.ts file when we try to create a new component from the command line.

You will find a reference to the newly created component in app.module.ts.

Time has come for us to check out the freshly created file in the new component.

new-component.component.ts

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

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

  constructor() { }

  ngOnInit() {
  }

}

Importing the core has become a necessity here. We have used the component reference in the decorator.

The decorator is equipped with a selector named app new component and the styleUrl and templateUrl.

Combine Angular Files Together to Bring Component to Life.

Time has come for us to check out the new-component.component.html below –

<p>
  new-component works!
</p>

As is evident in the HTML code above, we have the p tag. At present, the style file is empty given we don’t need any styling at this point. But when we run the project, we will not come across the effect of the new component displayed on the browser. So let’s add something at this point – it will be visible later on the browser.

We need to add app new component (the selector) in the app.component.html. Refer the code below…

<app-new-component></app-new-component>

We will be adding the tag. As a result, everything which is present in the .html file will be finally visible on the browser related to the newly created component. It will also fetch things from the parent component data.

Time for us to check out the new-component.component.html file.

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
  <p>
    new-component works!
  </p>

</div>

We have added a variable named new component in the class. The value assigned to the variable is “Hello, I’m the new component created by God!”.

You will find the aforementioned variable in the new-component.component.html file.
Refer the code below –

At present we have included the selector in the app.component.html. if you remember, this .html is the parent component .html. The actual content of the new-component.component.html will be displayed on the browser as below –

Angular Component Demo

Just as we explored in this example, we will be able to create more components like this. And the linking will be achieved with the help of selectors.

To know more about Angular and its feature visit angular.io.