https://www.tektutorialshub.com/angular/angular-component/
In this tutorial, we are going to look at Angular Components.
We will look at the building blocks of the components
and the important metadata properties of Angular Components
like selector, template, styleURL, etc.
We also show you how to create a simple component in Angular.
This tutorial is a continuation, of the tutorial Create Your First Angular Application.
You can download the source code from the GitHub Repository.
The starting code is found under the folder Getting Started and final source code is
in the folder Components
1. What is an Angular Component
The Component is the main building block of an Angular Application.
The Component contains the data & user interaction logic that defines how the View looks and behaves. A view in Angular refers to a template (HTML).
The Angular Components are plain JavaScript classes and defined using @Component Decorator. This Decorator provides the component with the View to display & Metadata about the Component
The Component is responsible to provide the data to the view. The Angular does this by using data binding to get the data from the Component to the View. This is done using the special HTML markup knows as the Angular Template Syntax. The Component can also get notified when the View Changes.
The Angular applications will have lots of components. Each component handles a small part of UI. These components work together to produce the complete user interface of the application
The Components consists of three main building blocks
- Template
- Class
- MetaData
![](https://blog.kakaocdn.net/dn/bWCA2K/btrqM43NR8H/kvybjdtK8FA6Bcbf5rz4V1/img.png)
2. Building blocks of the Angular Components
Template (View)
The template defines the layout and content of the View. Without the template, there is nothing for Angular to render to the DOM.
The Templates are nothing but HTML codes along with the Angular specific special HTML markups ( knows as the Angular Template Syntax).
You can add Angular directives , Angular Pipes & Other Angular Components on the template.
The data to Template comes from the Component, which in turn gets it from a Angular Service. Using the data binding techniques, we can keep the Template in sync with the Component. The templates can use the Event Binding or two way data binding to notify the component, when user changes something on the View.
There are two ways you can specify the Template in Angular.
- Defining the Template Inline
- Provide an external Template
Class
The Class provides the data & logic to the View. It contains the JavaScript code associated with Template (View). We use TypeScript to create the class, but you can also use JavaScript directly in the class.
Class Contains the Properties & Methods. The Properties of a class can be bind to the view using Data Binding.
The simple Angular Class
1
2
3
4
5
6
|
export class AppComponent
{
title : string ="app"
}
|
By convention we prefix the Component class with Component so as to easily identify them.
Metadata
Metadata Provides additional information about the component to the Angular. Angular uses this information to process the class. We use the @Component decorator to provide the Metadata to the Component.
@Component decorator
A decorator is a function that adds metadata to class, its methods & to its properties. The Components are defined with a @Component class decorator.
When Angular sees a class with @Component decorator, it treats the class as Component.
A Decorator is always prefixed with @. We must place the Decorator immediately before the class definition. We can also build our own decorators. The decorators are Similar to attributes in C#
Important Component metadata properties
Selector
Selector specifies the simple CSS selector. The Angular looks for the CSS selector in the template and renders the component there.
Providers
The Providers are the Angular Services, that our component going to use. The Services provide service to the Components or to the other Services.
Directives
The directives that this component going to use are listed here.
Styles/styleUrls
The CSS styles or style sheets, that this component needs. Here we can use either external stylesheet (using styleUrls) or inline styles (using Styles). The styles used here are specific to the component
template/templateUrl
The HTML template that defines our View. It tells Angular how to render the Component’s view. The templates can be inline (using a template) or we can use an external template (using a templateUrl). The Component can have only one template. You can either use inline template or external template and not both
3. Creating the Component
We have already shown how to create the Angular Application using Angular CLI in how to create first Angular application tutorial. The Angular CLI has automatically created the root component app.component.ts.
In this tutorial, we will not create the Angular Component, but let us see the Component creation process in detail. The creation of the Angular component requires you to follow these steps
- Create the Component file
- Import the required external Classes/Functions
- Create the Component class and export it
- Add @Component decorator
- Add metadata to @Component decorator
- Create the Template
- Create the CSS Styles
- Register the Component in Angular Module
1. Creating the Component File
The Component app.component.ts. is already been created for us by Angular CLI under the folder src.
By Convention, the file name starts with the feature name (app) and then followed by the type of class (component). These are separated by a dot. The extension used is ts indicating that this is a typescript module file.
You can read more about naming conventions from the Angular Style Guide
2. Import the Angular Component Library
Before we use any Angular (or external) functions or classes, we need to tell Angular how and where to find it. This is done using the Import statement. The Import statement is similar to the using statement in c#, which allows us to use the external modules in our class
To define the Component class, we need to use the @Component decorator. This function is part of the Angular Core library. So we import it in our class as shown below
1
2
3
|
import { Component } from '@angular/core';
|
3. Create the Component Class and export it
The third step is to create the Component class using the export keyword. The Export keyword allows other components to use this component importing it. The AppComponent class is shown below
1
2
3
4
5
|
export class AppComponent {
title = 'app';
}
|
Note we are using Pascal case naming conventions for the class name. In the above class defines a Property named title and assign a default value “app”
4. Add @Component decorator
The next step is to inform the Angular that this is a Component class. We do that by adding the @Component decorator. We must add the decorator immediately above the class definition.
1
2
3
4
5
6
7
|
@Component({
})
export class AppComponent {
title = 'app';
}
|
5. Add meta data to @Component decorator
The next step is to add the metadata to the component using the @component decorator. Add the following to the component metadata
1
2
3
4
5
6
7
|
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
|
selector
The angular places the view (template) inside the selector app-root
templateUrl
In the above example, we have used an external template using templateUrl metadata. The templateUrl points to the external HTML file app.component.html.
styleUrls
Defines the styles for our template. The metadata points to the external CSS file app.component.css. The Component specific CSS styles can be specified here
6. Create the Template (View)
Template is nothing but an HTML file, which component must display it to the user
The Angular knows which template display, using the templateUrl metadata, which points to app.component.html.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
Welcome to {{title}}!
</h1>
<img width="300" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAgMjUwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojREQwMDMxO30NCgkuc3Qxe2ZpbGw6I0MzMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZGRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdDAiIHBvaW50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjMgMTI1LDIzMCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbnRzPSIxMjUsMzAgMTI1LDUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGNsYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMUw2Ni44LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LTQwLjlMMTQyLDEzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo=">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
<li>
</li>
<li>
<h2><a target="_blank" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
</li>
<li>
</li>
</ul>
|
By Convention, the file is named after the component file it is bound to with HTML extension.
This is a simple HTML file, except for the initial h1 tag
1
2
3
4
5
|
<h1>
Welcome to {{title}}!
</h1>
|
Note that title inside the double curly bracket. When rendering the view, the Angular looks for title Property in our component and binds the property to our view. This is called data binding.
The double curly bracket syntax is known as interpolation, which we will look at in our next tutorial
7. Add the Styles
The next step is to add the CSS Styles. The styleUrls metadata tells Angular, where to find the CSS File. This property points to external file app.component.css
By convention, we name the file after the component file with .css extension
Note that styleUrls metadata can accept multiple CSS Files.
8. Register the Angular Component in Angular Module
We have created the Angular Component. The next step is to register it with the Angular Module
The Angular Module organizes the components, directives, pipes, and services that are related and arrange them into cohesive blocks of functionality.
We use @NgModule class decorator to define a Angular Module and provide metadata about the Modules.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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 declaration arrays is where we include the components, pipes and directives that are part of this module.
We add all the other Angular Modules that this module uses in the imports array.
Include all the Angular Services that are part of this module in the providers‘ array.
The Component that angular should load, when the app.module is loaded is assigned to the bootstrap property.
The AppComponent imported
1
2
3
|
import { AppComponent } from './app.component';
|
and then added to the declarations array.
1
2
3
4
|
@NgModule({
declarations: [ AppComponent ],
|
We want appComponent to be loaded when Angular starts, thus we assign it to bootstrap property
1
2
3
|
bootstrap: [AppComponent]
|
Thats it
Finally, run the application from the command line using ng serve ( or npm start). You should see this
![](https://blog.kakaocdn.net/dn/cxc8i6/btrqPiNMzqk/Ko4ZPvIQ4dcmwaKKDrKk8K/img.png)
4. Creating the inline Template & StyleUrls
In the above example, we have used the external template & Styles.
We can also specify the Template, Styles inline using the template and styles property of @Component metadata as shown below.
1
2
3
4
5
6
7
8
9
10
11
12
|
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<h1> {{title}} works </h1>',
styles: ['h1 { font-weight: bold; }']
})
export class AppComponent {
title = 'app';
}
|
The Template can get pretty long. In the case of a Multi-line template, you can use BackTicks ( ` ) to enclose the template string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1> {{title}} works </h1>
<p> a long inline template </p>
`,
styles: ['h1 { font-weight: bold; }']
})
export class AppComponent {
title = 'app';
}
|
Specifying the Templates and styles inline has few disadvantageous. The Template can get pretty big and clutter your code. You will also not get the IntelliSense help while editing the template. In such a case you can write your Html template in an external file and link that file in your component code.
5. The Component selector
The Angular renders the components view in the DOM inside the CSS selector, that we defined in the Component decorator
1
2
3
4
|
@Component({
selector: 'app-root',
|
The selector <app-root></app-root> is in the index.html (under src folder)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!doctype html>
<html lang="en">
<head>
<metacharset="utf-8">
<title>Angular4</title>
<basehref="/">
<metaname="viewport"content="width=device-width, initial-scale=1">
<linkrel="icon"type="image/x-icon"href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
|
When we build Angular Components, we are actually building new HTML elements. We specify the name of the HTML element in the selector property of the component metadata. And then we use it in our HTML.
The Angular looks for the selector in the current view. If it finds a selector, it renders the view of the component that is associated with that selector at that location.
Remember Angular is Single Page application (SPA)
The only page is shown to you is index.html. Components are added and removed from the index.html
Contents of app.component.html is inserted into the location <app-root></app-root>. Because app-root is the selector we used for the AppComponent. AppComponent is the first component that Angular loads, hence it is our Root Component.
The app.component.html may refer to <customer-list></customer-list>. The Angular looks for the component (for example CustomerListComponent) with selector customer-list and renders it there. This component now becomes the child component of the AppComponent.
The Template of CustomerListComponent may include more selectors. The Angular recursively going to look for them and renders them. They will become child of CustomerListComponent.
This will create a tree of components. You can refer to the tutorial on how to create a child component from our tutorial Angular child component
There are several ways you can specify the Component selector
Using the CSS class name
1
2
3
4
5
|
@Component({
selector: '.app-root'
})
|
And in the HTML markup use the CSS class name
1
2
3
|
<div class="app-root"></div>
|
Using attribute name
1
2
3
|
@Component({ selector: '[app-root]' })
|
And you can now the attribute as follows
1
2
3
|
<div app-root></div>
|
Using attribute name and value
1
2
3
4
5
|
@Component({
selector: 'div[app=components]'
})
|
now you can use it as follows
1
2
3
|
<div app="components"></div>
|
6. Summary
We looked at how to create an Angular Component in this tutorial. In the Next Tutorial, we look at How Component communicates with the View using Data Binding
'Angular JS' 카테고리의 다른 글
Interpolation in Angular (0) | 2022.01.15 |
---|---|
Data Binding in Angular (0) | 2022.01.15 |
Bootstrapping in Angular: How It Works Internally (0) | 2022.01.15 |
How to Create a new project in Angular (0) | 2022.01.15 |
How to Install Angular and Set Up Development Environment (0) | 2022.01.15 |
댓글