Lab 3 - Working With Variables
Intro
In this lab we will define and use an interface for a custom data type, and see how to do basic data binding in components
1. Create an interface
-
Create a new folder called
data. -
Inside this folder create a file called
SongInterface.tswith the following content;
export interface SongInterface {
id : number
title: string
artist: string
dateReleased: Date
price: number
}
*Note that you would normally note use the word "Interface" in the file / object name, however because we have a component also called Song, we are doing so in this example to keep things clear
2. Create objects from the interface
- In the song-list component, create 3 objects called song1, song2, song3, using the interface.
Click here to see a sample solution
export class SongListComponent {
song1 : SongInterface = {id: 1, title:"Billie Jean", artist: "Michael Jackson", dateReleased: new Date(1983,1,2), price: 10.99};
song2 : SongInterface = {id: 2, title:"I don't wanna miss a thing", artist: "Aerosmith", dateReleased: new Date(1998,5,2), price: 9.99};
song3 : SongInterface = {id: 3, title:"My heart will go on", artist: "Celine Dion", dateReleased: new Date(1997,11,19), price: 7.99};
}
3. Make a component property
- Adjust the song component so that it has a required parameter of type SongInterface
Click here for a sample solution
export class SongComponent {
song = input.required<SongInterface>();
}
- Edit the song component's HTML so that it renders the id, title and author inside an
litag.
Click here for a sample solution
<li>
ID: {{song().id}} TITLE: {{song().title}} ARTIST: {{song().artist}}
</li>
4. Pass data into a component
-
Edit the song-list component's html so that the song objects bind the song property to each of the song parameters.
-
Wrap the output in a
ultag
Click here for a sample solution
<ul>
<app-song [song]="song1"></app-song>
<app-song [song]="song2"></app-song>
<app-song [song]="song3"></app-song>
</ul>