Angular Labs
COOKIES

Component inputs

Git diff Branch

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 AlertBannerComponent class, then pass the data through the TaskList and TaskForm templates.

Instructions
  1. Update the AlertBannerComponent class:

    import { 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.component.ts file:

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

    <app-alert-banner message="Hello World" />
  4. Update the template of task-form.component.ts file:

    <app-alert-banner message="Hello World" />
  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.

Instructions
  1. Update the AlertBannerComponent class:

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

    Note

    The available classes are alert-info and alert-error, not just info and error. So we need to use a template literal to build the class name.

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

    <app-alert-banner message="Hello World" type="error" />
  4. Update the template of task-form.component.ts file:

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