What does Angular Ivy specifically allow us to do in regards to manual change detection?

浪子不回头ぞ 提交于 2021-02-06 08:58:11

问题


This article mentions that

Ivy opens a few possibilities for the future though. It should now be possible to run an application without zone.js, and to semi-manually handle change detection (a bit like you would with React). These APIs already exist but are experimental, not documented, and will probably change in the near future.

I think it was already possible to run an application without zone.js prior to Ivy. Does Ivy allow to semi-manually handle change detection? Where are those experimental APIs? Any doc? Does Ivy still use zone.js?

My goal is to limit change detections to a minimum by triggering them manually. What is the best option to do that. Specifically what is the best option when using Ivy.


回答1:


That's a huge topic to cover here, but I'll try to answer.

The idea is actually rendering components without declaring them inside any module.

Why would we wanna do something like that? It simple - Modules are much more than just components. Modules have zones, providers, injectors, DI, and much more. Modules for a lot of us represent applications. And sometimes we just want to create a simple component and render it in another component.

What's the problem it will cause? Modules are the one who sets up zones for us. Zones are the ones who trigger change detection automatically. If we will render a component outside a module, we won't have automatic change detection.

So, with Ivy, we have a few new APIS that can help us:

ɵrenderComponent() - That can render a component without declaring it in a module.

ɵdetectChanges(); - To trigger change detection manually, but, it's just a function from @angular/core and you don't need the DI any more to inject the ChangeDetectorRef

ɵmarkDirty() - To mark the component to check in the next change detection cycle.

ɵɵdirectiveInject() - Inject an InjectionToken in a matter of function, without using the constructor.

If you asking what is this ɵ sign that prefix all those new APIs, that means those functions are still experimental and you shouldn't use them for production yet. And that's also why they are not documented.

For your question - if you want to minimize the use of CD in your components, just render them with renderComponent function, and handle CD by yourself.

If you want to read more, I wrote a complete blog post exactly about this topic, including a lot of code examples. You can find it here - "The future of standalone components in post Ivy release days"

I also gave a talk about it in NG-DE 2019 - "Bye Bye NgModules"



来源:https://stackoverflow.com/questions/58784993/what-does-angular-ivy-specifically-allow-us-to-do-in-regards-to-manual-change-de

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!