Component inputs
Component inputs
Section titled “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.
Instructions
Section titled “Instructions”-
Update the
AlertBanner
class:alert-banner.ts import { Component, 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.html
file:<div role="alert" class="alert alert-vertical alert-info alert-soft"><span>{{ message() }}</span></div> -
Update the template of
task-list.html
file:<app-alert-banner message="Hello Task List" /> -
Update the template of
task-form.html
file:<app-alert-banner message="Hello Task Form" /> -
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
Section titled “Instructions”-
Update the
AlertBanner
class:type = input.required<"info" | "error">(); -
Update the template of
alert-banner.html
file:NoteThe available classes are
alert-info
andalert-error
, not justinfo
anderror
. 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.<divrole="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> -
Update the template of
task-list.html
file:<app-alert-banner message="Hello Task List" type="error" /> -
Update the template of
task-form.html
file:<app-alert-banner message="Hello Task Form" type="info" /> -
Test the application.