【问题标题】:How can I change content page based on mat option -Angular-如何根据 mat 选项更改内容页面 -Angular-
【发布时间】:2020-05-27 15:44:19
【问题描述】:

我正在开发一个 Angular 7 项目,现在我必须开发一个页面结构,其中包含上部和静态部分,用户可以使用 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>

如何根据选择动态控制内容?

提前感谢您,如果您需要更多详细信息,请告诉我。

【问题讨论】:

    标签: angular angular-material angular-material-7


    【解决方案1】:

    您可以使用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

    【讨论】:

    • 感谢您的回复,瓦莱里!我的需要是在我想用 ng-container 或 ng-template 带给我的不同内容之间切换。将它们视为表单组。如何在它们之间切换?
    • @R.Milos 我也添加了&lt;ng-template&gt; 示例,希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    相关资源
    最近更新 更多