Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Angular Cookbook

You're reading from   Angular Cookbook Over 80 actionable recipes every Angular developer should know

Arrow left icon
Product type Paperback
Published in Aug 2021
Publisher Packt
ISBN-13 9781838989439
Length 652 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Muhammad Ahsan Ayaz Muhammad Ahsan Ayaz
Author Profile Icon Muhammad Ahsan Ayaz
Muhammad Ahsan Ayaz
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: Winning Components Communication 2. Chapter 2: Understanding and Using Angular Directives FREE CHAPTER 3. Chapter 3: The Magic of Dependency Injection in Angular 4. Chapter 4: Understanding Angular Animations 5. Chapter 5: Angular and RxJS – Awesomeness Combined 6. Chapter 6: Reactive State Management with NgRx 7. Chapter 7: Understanding Angular Navigation and Routing 8. Chapter 8: Mastering Angular Forms 9. Chapter 9: Angular and the Angular CDK 10. Chapter 10: Writing Unit Tests in Angular with Jest 11. Chapter 11: E2E Tests in Angular with Cypress 12. Chapter 12: Performance Optimization in Angular 13. Chapter 13: Building PWAs with Angular 14. Other Books You May Enjoy

How to use *ngIf and *ngSwitch together

In certain situations, you might want to use more than one structural directive on the same host—for example, a combination of *ngIf and *ngFor together. In this recipe, you'll learn how to do exactly that.

Getting ready

The project we are going to work with resides in chapter02/start_here/multi-structural-directives, inside the cloned repository:

  1. Open the project in VS Code.
  2. Open the terminal, and run npm install to install the dependencies of the project.
  3. Once done, run ng serve -o.

    This should open the app in a new browser tab, and you should see something like this:

Figure 2.6 – multi-structural-directives app running on http://localhost:4200

Figure 2.6 – multi-structural-directives app running on http://localhost:4200

Now that we have the app running, let's see the steps for this recipe in the next section.

How to do it…

  1. We'll start by moving the element with the No items in bucket. Add some fruits! text into its own <ng-template> element, and we'll give it a template variable called #bucketEmptyMessage. The code should look like this in the app.component.html file:
    …
    <div class="content" role="main">
     ...
      <div class="page-section">
        <h2>Bucket <i class="material-icons">shopping_cart     </i></h2>
        <div class="fruits">
          <div class="fruits__item" *ngFor="let item of       bucket;">
            <div class="fruits__item__title">{{item.name}}        </div>
            <div class="fruits__item__delete-icon"         (click)="deleteFromBucket(item)">
              <div class="material-icons">delete</div>
            </div>
          </div>
        </div>
      </div>
      <ng-template #bucketEmptyMessage>
        <div class="fruits__no-items-msg">
          No items in bucket. Add some fruits!
        </div>
      </ng-template>
    </div>
  2. Notice that we moved the entire div out of the .page-section div. Now, we'll use the ngIf-Else syntax to either show a bucket list or an empty bucket message based on the bucket's length. Let's modify the code, as follows:
    ...
    <div class="content" role="main">
      ...
      <div class="page-section">
        <h2>Bucket <i class="material-icons">shopping_cart     </i></h2>
        <div class="fruits">
          <div *ngIf="bucket.length > 0; else       bucketEmptyMessage" class="fruits__item"       *ngFor="let item of bucket;">
            <div class="fruits__item__title">{{item.name}}        </div>
            <div class="fruits__item__delete-icon"         (click)="deleteFromBucket(item)">
              <div class="material-icons">delete</div>
            </div>
          </div>
        </div>
      </div>
    ...
    </div>

    As soon as you save the preceding code, you'll see the application breaks, mentioning we can't use multiple template bindings on one element. This means we can't use multiple structural directives on one element:

    Figure 2.7 – Error on console, showing we can't use multiple directives on one element

    Figure 2.7 – Error on console, showing we can't use multiple directives on one element

  3. Now, as a final step, let's fix the issue by wrapping the div with *ngFor="let item of bucket;" inside an <ng-container> element and using the *ngIf directive on the <ng-container> element, as follows:
    ...
    <div class="content" role="main">
      ...
      <div class="page-section">
        <h2>Bucket <i class="material-icons">shopping_cart     </i></h2>
        <div class="fruits">
          <ng-container *ngIf="bucket.length > 0; else       bucketEmptyMessage">
            <div class="fruits__item" *ngFor="let item         of bucket;">
              <div class="fruits__item__title">{{item.          name}}</div>
              <div class="fruits__item__delete-icon"           (click)="deleteFromBucket(item)">
                <div class="material-icons">delete</div>
              </div>
            </div>
          </ng-container>
        </div>
      </div>
    </div>

How it works…

Since we can't use two structural directives on a single element, we can always use another HTML element as a parent to use the other structural directive. However, that adds another element to the DOM and might cause problems for your element hierarchy, based on your implementation. <ng-container>, however, is a magical element from Angular's core that is not added to the DOM. Instead, it just wraps the logic/condition that you apply to it, which makes it really easy for us to just add a *ngIf or *ngSwitchCase directive on top of your existing elements.

See also

You have been reading a chapter from
Angular Cookbook
Published in: Aug 2021
Publisher: Packt
ISBN-13: 9781838989439
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image