Pra*_*esh 4 dom dom-manipulation angular-components angular
我可以这样做
<my-awesome-component *ngIf="ConditionToIncludeComponent"></my-awesome-component>
Run Code Online (Sandbox Code Playgroud)
但是动态插入组件的每个文档都基于ViewContainerRef.我喜欢它的功能.但是什么使它在*ngif上如此特别?
只需指出两者的优点和缺点.请.谢谢!
如果您在使用此模板时不知道组件模板中将使用哪个组件viewContainerRef.如果您事先知道该组件但有时可能会被隐藏,请使用ngIf.
ViewContainerRef用于指定动态组件的插入点.使用时ngIf需要在指定组件html 提前.因此,如果您有一个位置,您将插入三个组件之一,您将需要执行以下操作:
<my-awesome-component1 *ngIf="ConditionToIncludeComponent1"></my-awesome-component1>
<my-awesome-component2 *ngIf="ConditionToIncludeComponent2"></my-awesome-component2>
<my-awesome-component3 *ngIf="ConditionToIncludeComponent3"></my-awesome-component3>
Run Code Online (Sandbox Code Playgroud)
而viewContainerRef您只需要一个点(通常使用`ng-container指定).使用ngComponentOutlet可以这样做:
template: `<ng-container ngComponentOutlet="componentToInsert"></ng-container>`
class MyComponent {
const myAwesomeComponent1 = cfr.resolveComponentFactory(MyAwesomeComponent1);
const myAwesomeComponent2 = cfr.resolveComponentFactory(MyAwesomeComponent1);
const myAwesomeComponent3 = cfr.resolveComponentFactory(MyAwesomeComponent1);
if (ConditionToIncludeComponent1) {
componentToInsert = myAwesomeComponent1;
else if (ConditionToIncludeComponent2) {
componentToInsert = myAwesomeComponent2;
else if (ConditionToIncludeComponent3) {
componentToInsert = myAwesomeComponent3;
Run Code Online (Sandbox Code Playgroud)
或者使用createComponent方法手动组件:
template: `<ng-container #spot></ng-container>`
class MyComponent {
@ViewChild('spot', {read: ViewContainerRef}) vc;
const myAwesomeComponent1 = cfr.resolveComponentFactory(MyAwesomeComponent1);
const myAwesomeComponent2 = cfr.resolveComponentFactory(MyAwesomeComponent1);
const myAwesomeComponent3 = cfr.resolveComponentFactory(MyAwesomeComponent1);
if (ConditionToIncludeComponent1) {
vc.createComponent(myAwesomeComponent1);
else if (ConditionToIncludeComponent2) {
vc.createComponent(myAwesomeComponent2);
else if (ConditionToIncludeComponent3) {
vc.createComponent(myAwesomeComponent3);
Run Code Online (Sandbox Code Playgroud)
除了不便和臃肿的html模板之外,该ngIf方法的更大问题是性能影响,因为三个ngIf指令必须在每个变化检测周期上执行一些逻辑.
欲了解更多信息:
| 归档时间: |
|
| 查看次数: |
1256 次 |
| 最近记录: |