I am continuing my Learning
journey and understanding Angular’s
I will extend my current example and show more images when typing keywords into a text field.
You will understand how
ngFor works and how it can reduce code
duplication, especially in the template.
This article will take you less than four minutes to read.
We can implement showing/hiding items based on a boolean value using
ngIf, a possible implementation would be:
For two items, this implementation is fine. When there are more than
three items, say:
cow, the above
implementation starts to look like:
Displaying four items requires thirteen lines of code in the template. If there are more, this approach becomes unwieldily.
ngFor to the Rescue
Angular has another structural
that is equivalent to a
for loop in other programming languages.
Before we start, instead of having:
show_<item> variable in our
component code, I will put everything into a better data structure for
the data and its intended usage.
this.words refer to the above data
Before attacking the problem directly, lets use just
ngFor to solve
Listing out the words available for the text box will make this interaction more user-friendly.
The component code:
This displays in the browser:
ngFor with this new data structure, it’s easy to display all
the available options. When adding more items to the data structure,
there’s nothing to change in other parts of the code.
To iterate every
item in an
item_list array using
ngFor returns every element in
out words, I used:
word_list to store all the words from the
Object.keys(words). Why not use that?
ngFor in the template does not allow complex expressions, such as:
items is an object containing items. The way I solved this is
item_list in the component that stores the items:
Displaying Images with
As we can easily list all the words out supported, how can we display the images associated with them?
The image tag needs to use
ngIf to show when
true. For example:
Repeating this each time would just be the same as the initial implementation.
It’s down from thirteen lines to eight lines, so there is an improvement.
Can we do better?
ngFor, there is a better way!
ngFor, to display all the images where the
true, the code can be:
In the twice the number of lines as showing one image, we can display
all the proper images, even when adding more entries to
ngFor with the right data structure allows for efficient
processing of lists.
for syntax and
available in the template for simple evaluation.