Nur
Nur

Reputation: 67

Angular display div on option select, hide others

I want to display a div(mat-card) if an option is selected and hide the other divs if they are not selected

Template

<mat-form-field>
  <mat-label>Select an option</mat-label>
  <mat-select [(value)]="selected">
    <mat-option>None</mat-option>
    <mat-option value="General notifications">General notifications</mat-option>
    <mat-option value="Unread notifications">Unread notifications</mat-option>
    <mat-option value="Read notifications">Read notifications</mat-option>
  </mat-select>
</mat-form-field>

<p>You selected: {{selected}}</p>

<mat-card>These are the unread notifications</mat-card>
<mat-card>These are the read notifications</mat-card>
<mat-card>These are the general notifications</mat-card>

Controller

selected = 'General notifications';

Upvotes: 1

Views: 894

Answers (1)

kebab-case
kebab-case

Reputation: 1852

One (non-elegant) way to do it would be to add *ngIf to each of your mat-cards like so:

<mat-card *ngIf="selected === 'General notifications'">These are the general notifications</mat-card>
<mat-card *ngIf="selected === 'Unread notifications'">These are the unread notifications</mat-card>
<mat-card *ngIf="selected === 'Read notifications'">These are the read notifications</mat-card>

However, a better way to do it I would say is have a member variable in your .ts file that is an object/map of key-value pairs. The keys will be option values (eg 'General notifications') and the values will contain your desired text for the selected option.

For example

notificationMap = {
  'General notifications': 'These are ...',
  'Unread notifications': 'These are...',
  'Read notifications': 'These are...',
}

Then in your .html you can simply do this:

<mat-card>{{notificationMap[selected]}}</mat-card>

Upvotes: 2

Related Questions