Submodule 19.3: Angular Components
Submodule 19.3: Angular Components
- Component
- Interpolation
- Structural directives
- Pipes
... Components Part 1...
Creating the Menu
Next, create a folder
named shared
under the src/app folder
. We will put here files that we're going to share across various components.
To this folder, add a file
named dish.ts
with the following code, to create and export a class that defines the Choco-dish object. This class will act as a blueprint for the objects that we will create next :
Update menu.component.ts
as follows to add in the data for four kinds of chocolate.
By importing the class "dish", we can use it as a type for the array of objects "dishes", that we will define and export for the next step. With the phrase "as a type" we mean that the data inserted in "dishes" objects, should be of the same type with those that are declared on "dish" class. For example, in this case we cannot have a number as a value.
Next, update the menu.component.html
template as follows:
Note the syntax, *ngfor, which is the structural directive in Angular.
It allows us to iterate over an array of items.
Remember that we have defined and exported dishes as an array of dish objects in our code.
In the template, we iterate over it, using the code *ngFor="let dish of dishes"
which allows us to access each element of the array.( dish is just a name, it could be anything eg i,x,w..)
This is like a for loop.
Now from this, we can also get access to the properties of each individual object inside the dishes array.
Note the double curly brackets, for example, in {{dish.image}}
. This is the one-way interpolation. Using double curly brackets we can display the value of the dish.image in our page.
This means that the source of the image will get the value of dish.image that is defined in my javaScript object.
The same applies for all of {{dish.name}} etc.
Note the | (the vertical bar on your keyboard). This is an Angular pipe.
We use the uppercase pipe which will transform the dish.name from whatever it is into an entire word with uppercase letters.
we're going to use more angular pipes in the next submodules.