Search code examples
angularangular-materialangular-material-7

How can I change content page based on mat option -Angular-


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.


Solution

  • 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