我试图实现根据所选的单选按钮在屏幕上显示不同的 View ,所有这些都使用 Angular Material 、NgModel
、NgIf
。但我做不到。请帮忙。
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/