Как я могу изменить страницу содержимого в зависимости от опции мата - Angular - - PullRequest
0 голосов
/ 27 мая 2020

Я работаю над проектом Angular 7, и теперь мне нужно разработать страницу, структурированную с помощью верхней и c части, где пользователь может выбирать между различными вариантами, используя компонент выбора материала mat-select. В зависимости от выбранной опции я хочу отображать другое содержимое на странице.

<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>

Как я могу управлять содержимым динамически на основе выбора?

Заранее благодарим вас и пожалуйста, дайте мне знать, если вам нужны более подробные сведения.

1 Ответ

1 голос
/ 27 мая 2020

Вы можете использовать ngSwitch для отображения различного содержимого в зависимости от выбранного значения:

<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


В случае если вы хотите использовать шаблоны в качестве содержимого, вы можете использовать директиву ngTemplateOutlet , чтобы вставить его.

<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

...