Component inputs
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
-
Update the
AlertBannerComponent
class:import { input } from "@angular/core";message = input.required<string>();NoteThe 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.
-
Update the template of
alert-banner.component.ts
file:<div role="alert" class="alert alert-vertical alert-info alert-soft"><span>{{ message() }}</span></div> -
Update the template of
task-list.component.ts
file:<app-alert-banner message="Hello World" /> -
Update the template of
task-form.component.ts
file:<app-alert-banner message="Hello World" /> -
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
-
Update the
AlertBannerComponent
class:type = input.required<"info" | "error">(); -
Update the template of
alert-banner.component.ts
file:NoteThe available classes are
alert-info
andalert-error
, not justinfo
anderror
. 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> -
Update the template of
task-list.component.ts
file:<app-alert-banner message="Hello World" type="error" /> -
Update the template of
task-form.component.ts
file:<app-alert-banner message="Hello World" type="info" /> -
Test the application.