javascript - 带有 Angular 6(Angular Material)单选按钮和 *ngIf 的显示元素

标签 javascript angular angular-reactive-forms

我试图实现根据所选的单选按钮在屏幕上显示不同的 View ,所有这些都使用 Angular Material 、NgModelNgIf。但我做不到。请帮忙。

HTML 代码:

<mat-radio-group [(ngModel)]="expressType">
  <mat-radio-button class="example-radio-button" *ngFor="let te of typeExpress" [value]="te">
    {{ te }}
  </mat-radio-button>
</mat-radio-group>

<ng-template *ngIf="te == 'Component 1'">
  <app-component1></app-component1>
</ng-template>
<ng-template *ngIf="te == 'Component 2'">
  <app-component2></app-component2>
</ng-template>
<ng-template *ngIf="te == 'Component 3'">
  <app-component3></app-component3>
</ng-template>

typescript 代码:

expressType: string;
typeExpress: string[] = ['Component 1', 'Component 2', 'Component 3'];

radioOptions: FormGroup; 

最佳答案

您应该使用 ng-container 而不是 ng-template 并使用 expressType 而不是 te 进行比较到 Component n 值。

试试这个:

<mat-radio-group [(ngModel)]="expressType">
  <mat-radio-button class="example-radio-button" *ngFor="let te of typeExpress" [value]="te">
    {{ te }}
  </mat-radio-button>
</mat-radio-group>

<ng-container *ngIf="expressType === 'Component 1'">
  <app-component1></app-component1>
</ng-container>
<ng-container *ngIf="expressType === 'Component 2'">
  <app-component2></app-component2>
</ng-container>
<ng-container *ngIf="expressType === 'Component 3'">
  <app-component3></app-component3>
</ng-container>

<h1>Or with ng-template</h1>

<ng-template [ngIf]="expressType === 'Component 1'">
  <app-component1></app-component1>
</ng-template>
<ng-template [ngIf]="expressType === 'Component 2'">
  <app-component2></app-component2>
</ng-template>
<ng-template [ngIf]="expressType === 'Component 3'">
  <app-component3></app-component3>
</ng-template>

<!-- Copyright 2018 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license -->
    enter code here
<小时/>

Here's a Working Sample StackBlitz for your ref.

关于javascript - 带有 Angular 6(Angular Material)单选按钮和 *ngIf 的显示元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54236821/

相关文章:

javascript - 如何动态添加 wmode=opaque 到已经显示的嵌入元素?

Angular:从 FormControl 获取所有验证器的列表

angular - 如何使用 set 控件方法填充 FormArray 的值?

javascript - 抑制 omniture s.t() 调用在带有 iframe 的站点中生成 "second"网页浏览

javascript - 搜索 2 个字符串中的占位符值

Angular Testing - 使用 rxjs switchMap 的链式 HTTP 请求

javascript - 未找到服务中的 Angular 7 类

angular - 架构验证失败,出现以下错误 : Data path ".builders[' app-shell' ]"should have required property ' class'

angular - 错误 TypeError : this. 验证器不是 FormArray 函数

javascript - Angular JS UI-Router 示例不起作用