您可以通过创建将有条件地呈现两个组件之一的组件来做到这一点。一个条件将加载info 组件,另一个条件将加载quantity 组件。让我们将此条件模式称为:food-modal,在food-modal.component.html 模板内,代码可能如下所示:
<h1>CONDITIONAL MODAL CONTAINER</h1>
<ng-container *ngIf="product.name === 'Chicken'">
<app-info [product]="product"></app-info>
</ng-container>
<ng-container *ngIf="product.name === 'Cow'">
<app-quantity [product]="product"></app-quantity>
</ng-container>
在food-modal.component.ts 内部,代码可能如下所示:
import { Component, OnInit, Input } from '@angular/core';
import { Product } from '../models/Product.model';
@Component({
selector: 'app-food-modal',
templateUrl: './food-modal.component.html',
styleUrls: ['./food-modal.component.css']
})
export class FoodModalComponent implements OnInit {
@Input()
public product: Product;
constructor() {}
ngOnInit() {}
}
你现在要做的就是在你想要的地方调用这个组件并传入Product模型。为了演示,我将把所有内容都放在app 组件中,以便加载food-modal。 app.component.html 可能看起来像:
<app-food-modal [product]="chickenProduct">
</app-food-modal>
app.component.ts 内部的代码可能是这样的:
import { Component } from '@angular/core';
import { Product } from './models/Product.model';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public chickenProduct: Product;
constructor() {
this.chickenProduct = {
id: 1,
quantity: 2,
name: 'Chicken'
};
}
}
现在app 组件会将名为chickenProduct 的Product 对象传递给food-modal 组件并将其绑定到模态的product 属性。之后会进行条件渲染。
其余代码可能如下所示:
info.component.html:
<p>
This modal is for INFO. Product name is: {{ product.name }}
</p>
info.component.ts:
import { Component, OnInit, Input } from '@angular/core';
import { Product } from '../models/Product.model';
@Component({
selector: 'app-info',
templateUrl: './info.component.html',
styleUrls: ['./info.component.css']
})
export class InfoComponent implements OnInit {
@Input()
public product: Product;
constructor() { }
ngOnInit() {
}
}
quantity.component.html:
<p>
This modal is for QUANTITY. Product name is: {{ product.name }}
</p>
quantity.component.ts:
import { Component, OnInit, Input } from '@angular/core';
import { Product } from '../models/Product.model';
@Component({
selector: 'app-quantity',
templateUrl: './quantity.component.html',
styleUrls: ['./quantity.component.css']
})
export class QuantityComponent implements OnInit {
@Input()
public product: Product;
constructor() { }
ngOnInit() {
}
}
product.model.ts:
export interface Product {
id: number;
quantity: number;
name: string;
}
我已经实施了这样的解决方案,一切正常!将产品的name 属性更改为Cow,条件触发将发生并加载quantity 组件,将其带回Chicken,条件触发将加载info 组件。
我假设您只是想知道如何触发条件触发,这就是为什么我通过硬编码字符串来完成此操作,检查产品名称是Chicken 还是Cow。