Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Creating Components in Angular

Components are the building blocks of Angular applications. This tutorial covers how to create components using the Angular CLI, and how to define their templates, styles, and behavior.

Creating a Component

You can create a new component using the Angular CLI. The CLI generates the necessary files and updates your module to include the new component.

Step 1: Generate the Component

ng generate component my-component

This command generates the following files:

  • my-component.component.ts: The component class.
  • my-component.component.html: The component template.
  • my-component.component.css: The component styles.
  • my-component.component.spec.ts: The component test file.

Component Class

The component class defines the behavior of the component. It is decorated with the @Component decorator, which specifies the component's metadata:

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

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  title: string = 'My Component';
}

Component Template

The template defines the HTML view of the component. It can be defined inline or in a separate HTML file:

<!-- my-component.component.html -->
<h2>{{ title }}</h2>
<p>This is my component!</p>

Component Styles

The styles define the CSS for the component. They can be defined inline or in a separate CSS file:

/* my-component.component.css */
h2 {
  color: blue;
}

p {
  font-size: 14px;
}

Using the Component

To use the component in your application, add its selector to the template of a parent component:

<!-- app.component.html -->
<app-my-component></app-my-component>

Component Interaction

Components can interact with each other using inputs and outputs:

Input

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: '<p>{{ message }}</p>'
})
export class ChildComponent {
  @Input() message: string;
}

Output

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: '<button (click)="sendMessage()">Send Message</button>'
})
export class ChildComponent {
  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    this.messageEvent.emit('Hello from Child!');
  }
}

Conclusion

Creating components is a fundamental part of developing Angular applications. By understanding how to generate components, define their templates and styles, and facilitate component interaction, you can build dynamic and reusable user interfaces. Happy coding!