我试图实现根据所选的单选按钮在屏幕上显示不同的视图,所有这些视图都使用Angular材质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;
答案 0 :(得分:1)
您应该使用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
这是您推荐的Working Sample StackBlitz。
答案 1 :(得分:0)
<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>
选项1
<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>
选项2
<ng-template [ngSwitch]="expressType'">
<app-component1 *ngSwitchCase="'Component 1'"></app-component1>
<app-component2 *ngSwitchCase="'Component 2'"></app-component2>
<app-component3 *ngSwitchCase="'Component 3'"></app-component3>
</ng-template>
选项3
<app-component1 *ngIf="expressType == 'Component 1'"></app-component1>
<app-component2 *ngIf="expressType == 'Component 2'"></app-component2>
<app-component3 *ngIf="expressType == 'Component 3'"></app-component3>
请注意,您是在比较 te 而不是模型值 expressType