Member-only story
Source:- Component in Angular
For more questions and answers visit our website at Frontend Interview Questions
In Angular, a component is a fundamental building block of the application’s user interface. It represents a part of the UI that controls a specific view and behavior. Components are typically composed of three main parts: the component class, the component template (HTML), and the component stylesheet (CSS).
Here’s an example of an Angular component:
Suppose we want to create a simple component to display information about a user:
- Create the component class:
// user.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-user', // The component selector used in HTML templates
templateUrl: './user.component.html', // The path to the HTML template file
styleUrls: ['./user.component.css'] // The path to the CSS styles for this component
})
export class UserComponent {
userName: string = 'test user';
age: number = 30;
}
2. Create the component template:
<!-- user.component.html -->
<div>
<h2>User Information</h2>
<p><strong>Name:</strong> {{ userName }}</p>
<p><strong>Age:</strong> {{ age }}</p>
</div>