Photo by Travel Sourced on Unsplash

How to Create a Component in Angular

Vanessa Martinez
3 min readJan 27, 2021

--

If you already know how to use React, like me, then you’ll find it easy to understand how to create a component in Angular. For those not familiar with the concept of a “component,” you can think of it as a way to compartmentalize chunks of code for particular use. Each component has its own template (HTML code), styling, and logic. This allows you to reuse the same code for different purposes and makes it simple to update.

The Root Component

If you take a look below, you’ll find the app component of my Angular project—app.component.html. It works as the root component, which means it’s what ultimately holds the entire application (other components).

Creating a New Component

If we want to create a component to house our server logic, we should first create a folder for “server.” By convention, each component should be placed inside its related folder (usually bearing the same name). So my folder will be “server,” and my component file will be named server.component.ts. We use TypeScript in Angular, so that’s why you append it with “ts.”

Next, we fill out our component. We want to import a component from the core functionalities of the Angular app, so we use the @angular/core package. Without that import line, we cannot create the component. The “Component” keyword on line 3 is preceded by the @ sign, which makes it a “decorator.” We use that syntax to declare the component decorator, which will ultimately parse the file and compile it to JavaScript.

Note: A component is a TypeScript class. This is important because Angular is able to instantiate it in order to create objects containing the information from the file. We export it at the end, so we have access to it in other parts of the program.

Next, we set up metadata within the component, so Angular has instructions on its functionality. We start by adding the selector, which works as an HTML tag, so you can use it in other components. Then, you add the templateUrl, which will point to an external file containing all of your HTML for that component.

Note: This is different from React, where your HTML (or JSX, rather) goes in the same file as your component.

So, once you create the html file within the same server folder and include the relative path, such as on line 5 above, you’re pretty much done. You’ve just created your first component in Angular.

--

--

Vanessa Martinez

Freelance Software Engineer. Experience in JavaScript, React.js, and Ruby on Rails.