0

I'm working on an Angular 7 project and now I have to develop a page structured with an upper and static part where user can choose between different options, using mat-select material component. Based on the option selected I want to show a different content in the page.

<div>
 <div>
  <mat-select>
    <mat-option>option1</mat-option>
    <mat-option>option2</mat-option>
    <mat-option>option3</mat-option>
  </mat-select>
 </div>
...here I want to change dinamically between content1 || content2 || content3 based on the selection above...
</div>

How can I control the content dinamically, based on the selection?

Thank you in advance, and please let me know if you need more detail.

R. Milos
  • 43
  • 1
  • 7

1 Answers1

1

You can use ngSwitch to display different content depending on the select value:

<mat-form-field>
  <mat-label>Select an option</mat-label>
  <mat-select #select>
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option value="option3">Option 3</mat-option>
  </mat-select>
</mat-form-field>
<ng-container [ngSwitch]="select.value">
  <p *ngSwitchCase="'option1'">The first option content</p>
  <p *ngSwitchCase="'option2'">The second option content</p>
  <p *ngSwitchCase="'option3'">The third option content</p>
</ng-container>

StackBlitz


In case you if you want to use templates as the content, you can use ngTemplateOutlet directive to insert it.

<mat-form-field>
  <mat-label>Select an option</mat-label>
  <mat-select #select>
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option value="option3">Option 3</mat-option>
  </mat-select>
</mat-form-field>
<ng-container [ngSwitch]="select.value">
  <ng-container *ngSwitchCase="'option1'">
    <ng-container *ngTemplateOutlet="firstContent"></ng-container>
  </ng-container>
  <ng-container *ngSwitchCase="'option2'">
    <ng-container *ngTemplateOutlet="secondContent"></ng-container>
  </ng-container>
  <ng-container *ngSwitchCase="'option3'">
    <ng-container *ngTemplateOutlet="thirdContent"></ng-container>
  </ng-container>
</ng-container>
<ng-template #firstContent><p>The first option content</p></ng-template>
<ng-template #secondContent><p>The second option content</p></ng-template>
<ng-template #thirdContent><p>The third option content</p></ng-template>

StackBlitz

Valeriy Katkov
  • 33,616
  • 20
  • 100
  • 123
  • Thank you for your reply, Valeriy!. My need is to switch between different content which I'd like to bring to me with an ng-container or ng-template. Think about them as form-group. How can I switch between them? – R. Milos May 28 '20 at 07:42
  • @R.Milos I added `` example too, hope it helps you. – Valeriy Katkov May 28 '20 at 08:04