Skip to content

Component inputs

The banner displays a message but not only it’s a placeholder unrelated to the application; we want the message to be different based on where it’s used:

  • in the TaskList component, we want to display a message proposing to delete all existing tasks
  • in the TaskForm component, we want to display a message inviting to prefill the form with basic information

Inputs are a way to pass data to the component, from the template where it’s used:

  • the TaskList component will pass a ‘delete’ message to the AlertBanner component
  • the TaskForm component will pass a different ‘prefill’ message to the AlertBanner component

We will define inputs to make the component more adaptable to different use cases.

We also call it a parent-child relationship: the parent is the component using the child in its own template.

We’ll firstly define these properties in the AlertBanner class, then pass the data through the TaskList and TaskForm templates.

  1. Update the AlertBanner class:

    alert-banner.ts
    import { Component, input } from "@angular/core";
    message = input.required<string>();
    Note

    The input is marked as required: it’ll throw an error if the parent component does not provide a value for it. In some situations, inputs are just optional.

  2. Update the template of alert-banner.html file:

    <div role="alert" class="alert alert-vertical alert-info alert-soft">
    <span>{{ message() }}</span>
    </div>
  3. Update the template of task-list.html file:

    <app-alert-banner message="Hello Task List" />
  4. Update the template of task-form.html file:

    <app-alert-banner message="Hello Task Form" />
  5. Test the application.

We’ll add another input, to dynamically define the type of alter: info or error. It’ll help us apply different CSS styles to the alert banner based on the type of message.

  1. Update the AlertBanner class:

    type = input.required<"info" | "error">();
  2. Update the template of alert-banner.html file:

    Note

    The available classes are alert-info and alert-error, not just info and error. We use Angular’s [class.className] binding to conditionally apply CSS classes based on the type value. The [class.className] syntax adds the class when the expression is true.

    <div
    role="alert"
    class="alert alert-vertical alert-soft"
    [class.alert-info]="type() ? type() === 'info' : false"
    [class.alert-error]="type() ? type() === 'error' : false"
    >
    <span>{{ message() }}</span>
    </div>
  3. Update the template of task-list.html file:

    <app-alert-banner message="Hello Task List" type="error" />
  4. Update the template of task-form.html file:

    <app-alert-banner message="Hello Task Form" type="info" />
  5. Test the application.