0
0
Angularframework~5 mins

Type annotations in components in Angular

Choose your learning style9 modes available
Introduction

Type annotations help Angular know what kind of data your component uses. This makes your code safer and easier to understand.

When you want to clearly say what type a variable or property holds in your component.
When you want to catch mistakes early by letting Angular check your data types.
When you want your code editor to give better suggestions and help while you write code.
Syntax
Angular
propertyName: type = initialValue;

Use a colon : after the property name to add a type.

You can assign an initial value after the type with =.

Examples
This means name is a string and starts with 'Alice'.
Angular
name: string = 'Alice';
This means age is a number and starts with 30.
Angular
age: number = 30;
This means isActive is true or false, starting as true.
Angular
isActive: boolean = true;
This means items is an array of strings.
Angular
items: string[] = ['apple', 'banana'];
Sample Program

This Angular component uses type annotations to define the types of its properties. It shows the user's name, age, and active status in the template.

Angular
import { Component } from '@angular/core';

@Component({
  selector: 'app-user-info',
  standalone: true,
  template: `
    <section>
      <h2>User Info</h2>
      <p>Name: {{ name }}</p>
      <p>Age: {{ age }}</p>
      <p>Active: {{ isActive }}</p>
    </section>
  `
})
export class UserInfoComponent {
  name: string = 'Alice';
  age: number = 30;
  isActive: boolean = true;
}
OutputSuccess
Important Notes

Type annotations do not change how the code runs but help catch errors while coding.

Angular uses TypeScript, so type annotations are part of TypeScript syntax.

Always use type annotations for better code clarity and fewer bugs.

Summary

Type annotations tell Angular what type each property holds.

They help catch mistakes early and improve code readability.

Use simple syntax: propertyName: type = value;