The ngSwitch Directive

In this lesson, we'll learn how the ngSwitch directive can help us conditionally render elements.

We'll cover the following

The next directive we’ll be looking at is the ngSwitch directive. In JavaScript, there are two ways to run code conditionally. There’s if/else and switch/case. The ngSwitch directive allows you to use the switch/case syntax in your templates.

Updating the data

We’re going to update our data in the app.component.ts file where each object in the images array will have a property called downloadable.

export class AppComponent {
  images = [
    {
      title: 'Title #1',
      url: 'https://images.unsplash.com/photo-1588750099599-09efbe4377ad?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80',
      downloadable: 1
    },
    {
      title: 'Title #2',
      url: 'https://images.unsplash.com/photo-1588598158189-3d6e4dade28b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80',
      downloadable: 2
    },
    {
      title: 'Title #3',
      url: 'https://images.unsplash.com/photo-1588607684532-1c4a7ab618f5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80',
      downloadable: 0
    },
    {
      title: 'Title #4',
      url: 'https://images.unsplash.com/photo-1588710277537-126980e8d44e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80',
      downloadable: 1
    },
    {
      title: 'Title #5',
      url: 'https://images.unsplash.com/photo-1588627541420-fce3f661b779?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80',
      downloadable: 2
    },
    {
      title: 'Title #6',
      url: 'https://images.unsplash.com/photo-1588607778482-2358f4f0be5d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1001&q=80',
      downloadable: 1
    }
  ];
}

The possible values for the property are 0, 1, and 2. 1 will mean the image is downloadable. 2 will mean the image is downloadable but must be purchased. Lastly, any other value will mean it’s not downloadable.

We’ll update the app.component.html template file to use the ngSwitch directive.

Get hands-on with 1400+ tech skills courses.