Angular Components

Angular Components

Components are the main building block for Angular applications.  Components are basically classes that interact with the .html file of the component. A component includes a TypeScript class with a @Component() decorator, an HTML template, and styles.

  • An HTML template that declares what renders on the page
  • A Typescript class that defines behavior
  • A CSS selector that defines how the component is used in a template
  • Optionally, CSS styles applied to the template

Angular Data Binding

Angular Event Binding

The angular components consists of the following files:

  • app.component.scss
  • app.component.html
  • app.component.spec.ts
  • app.component.ts
  • app.module.ts
ng generate component component name Or ng g c component name

When you run the above command in the command line, you will receive the following files:

C:\my-application>ng g component new-comp CREATE src/app/new-comp/new-comp.component.html (30 bytes) CREATE src/app/new-comp/new-comp.component.spec.ts (620 bytes) CREATE src/app/new-comp/new-comp.component.ts (300 bytes) CREATE src/app/new-comp/new-comp.component.scss (2 bytes) UPDATE src/app/app.module.ts (477 bytes

The following is a minimal Angular component.

import { Component } from '@angular/core'; @Component({ selector: 'new-comp', templateUrl: './new-comp.component.html', styleUrls: ['./new-comp.component.scss'] }) export class NewCompComponent implements OnInit { constructor() { } ngOnInit() { } }

NewCompComponent  is the component class. It contains properties and methods to interact with the view through an Angular API. It implements the OnInit interface, which is a lifecycle hook.

The @Component is a decorator used to specify the metadata for the component class defined immediately below it. It is a function and can include different configs for the component. It instructs Angular where to get required files for the component, create and render component. All Angular components must have @Component decorator above the component class.

The import statement gets the required feature from the Angular or other libraries. Import allows us to use exported members from external modules. For example, @Component decorator and OnInit interface are contained in @angular/core library. So, we can use them after importing it.