As I mentioned in a previous blog post, we have been working on a final project in our Software Design, Construction, and Architecture class, where we are constructing a single-page website that connects front-end and back-end components. I’ve been working on front-end elements most recently, and I got up close and personal with Angular structural directives (after debugging my code for almost 2 days). This link was my main reference when trying to fix my code: https://angular.io/guide/structural-directives.
Structural directives, like the name suggests, alter the structure of the HTML layout by changing individual elements in the document. The directive is simply added to the tag of the element to be altered, called the host element. Any descendants of this element will also be affected by the directive. For example, a tag with an ngIf directive would look something like: <div *ngIf=”true”>Hello there! (I didn’t add the ending div tag because this makes the whole tag disappear upon publishing this post)
There are three common directives used in HTML: ngIf, ngFor, and ngSwitch. ngIf takes in a Boolean expression as a string and displays the host element if the expression is true. For example, if the example tag from above was present in a document, the element would still display, and “Hello there!” would be visible.
ngFor is used as a repeater directive, where items in a list or array can be displayed by iteration, or a statement can be shown a certain number of times depending on however many iterations. The loop takes on Python syntax when expressed as a String for the ngFor directive. An example of ngFor would be: <p *ngFor = “let name of names”> This is a name.</p> The loop would iterate the same number of times as the number of names present in the list, and the statement would be displayed that many times as well.
Finally, ngSwitch operates like the switch statement in Java, where one variable’s value is checked, and depending on the value of that variable, one case will be executed, which is an element defined with that variable’s desired value. For example, if you’re trying to look up profiles for different users of a social media website, ngSwitch would work along the following lines: a profile variable would be set to whichever profile name you’d like to look at, and depending on the value you chose, that appropriate profile page would display.
This article was incredibly helpful for me to figure out how to conditionally display some of the elements on my webpage, and I am certain that I will use it later on for further reference!