Skip to main content

How do you declare a component in Angular?

In Angular, a component is declared using the decorator @Component above a class. A simple example:

typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-my-component', // tag name used in the template templateUrl: './my-component.component.html', // path to the HTML template styleUrls: ['./my-component.component.css'] // path to the styles }) export class MyComponent { title = 'Component example'; }

After that, the component needs to be added to the declarations array of the module (NgModule) so that Angular recognizes it:

typescript
@NgModule({ declarations: [MyComponent], imports: [...], bootstrap: [AppComponent] }) export class AppModule { }

Now the component can be used in templates via the tag <app-my-component></app-my-component>.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.