Learn about Component in Angular

In the previous tutorial, I had a basic explanation of what a Component in Angular is, what its functions. In this tutorial, I will go more about Component in Angular.

First, I will create an Angular project as an example:

Learn about Component in Angular

In Angular, a component is an HTML part of the entire HTML content that we need to build for our application.

For example, you have an HTML page like this:

then you can build a Component for this entire page, or split it into multiple components for each <div> tag.

In the project I just created, the AppComponent class in the src/app/app.component.ts file is a Component in Angular. The content of this class is as follows:

A Component class in Angular will be decorator with @Component decorator and there are two important attributes required of this decorator are selector and templateUrl.

Inside:

  • The selector attribute is used to declare the HTML tag that this Component will replace the content in our Angular application.
  • The templateUrl attribute defines the HTML content that this component will build.

The styleUrls attribute in our example is used to define CSS files for editing styles for this component. It is not required because we can define a generic CSS file for the entire Angular application.

In the AppComponent class, as you can see, it defines a title variable. This variable replaces the placeholder {{title}} in the app.component.html file:

Suppose we now need to build an HTML page:

I will replace the content of the file app.component.html into content on. Then run the application, I will see the results as follows:

Learn about Component in Angular

Now, I want to split the content into 2 different components. One for:

and one for:

I will do the following:

First, I will create 4 files named h1.component.html, h1.component.ts, p.component.html, and p.component.ts in the src/app directory as follows:

Learn about Component in Angular

The contents of the h1.component.html file will be retrieved from the app.component.html file as follows:

The contents of the p.component.html file will look like this:

The content of the app.component.html file at this time we will replace with the selector as follows:

Now, we will add 2 Component class as PComponent and H1Component in the files p.component.ts and h1.component.ts. Their contents are as follows:

PComponent

H1Component:

Then, we need to declare these two components to the AppModule:

Run the application again, you also see the same results.

Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment