Componentresolver vs * ngif in angular [英] Componentresolver vs *ngif in angular

查看:130
本文介绍了Componentresolver vs * ngif in angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我创建了一个动态组件



AppComponent.html



Below I have created a dynamic component

AppComponent.html

<input type="button" value="One" (click)="setVal('one')">
<input type="button" value="Two" (click)="setVal('two')">
<br>
<app-dynamic-component [key]="keyvalue"></app-dynamic-component>





AppComponent.ts < br $> b $ b



AppComponent.ts

keyvalue = 'one'

setVal(val) {
    this.keyvalue = val;
}





及其记录如下:



控制台登录





----------





以下使用`* ngIf`



AppComponent.html





and its logs the following:

Console log here


----------


And following are using `*ngIf`

AppComponent.html

<input type="button" value="One" (click)="setVal('one')">
<input type="button" value="Two" (click)="setVal('two')">
<br>
<app-component-one *ngIf="keyvalue=='one'"></app-component-one>
<app-component-two *ngIf="keyvalue=='two'"></app-component-two>





AppComponent。 ts





AppComponent.ts

keyvalue = 'one'

setVal(val) {
    this.keyvalue = val;
}





和日志:



这里的控制台记录





----------



两者都做同样的事情来创建和销毁子组件。使用 ComponentFactoryResolver 而不是 * ngIf 有什么好处,让我们说 * ngIf 完成工作,我应该使用 ComponentFactoryResolver 相反?



我尝试过:



已实施,但我很困惑哪个是更好的方法。



and the logs:

Console log here


----------

Both does the same thing of creating and destroying the child components. What is the advantage of using ComponentFactoryResolver over *ngIf and lets say *ngIf gets the job done, should I use ComponentFactoryResolver instead?

What I have tried:

Implemented both, but I am confused about which is the better way.

推荐答案

使用ComponentFactoryResolver这样一个简单的案例是过度的。至少你应该将你的工作组件(一个和两个)声明为EntryComponents,以便能够动态构造它们。



当您想要从指令创建组件时,ComponentFactoryResolver可能很有用。该指令没有模板,所以你不能* ngIf组件,唯一的方法是使用ComponentFactoryResolver。
Using ComponentFactoryResolver for such a simple case is overkill. At least you should declare your worker components (one and two) as EntryComponents to be able to construct them dynamically.

ComponentFactoryResolver may be useful when you want to create a component from directive for example. The directive has no template so you cannot *ngIf the component and the only way is to use ComponentFactoryResolver.


这篇关于Componentresolver vs * ngif in angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆