Repository navigation
Description
Note 1: This proposal has its origin in RFC: Exploration of use-cases for Angular JIT compilation mode and aims to address the concerns around AOT compiler not being flexible enough for very dynamic, or heavily data-driven UIs.
Note 2: 📺 Check out the video recording of a community discussion about this proposal @ angularnation.net
Description
While declarative templating is great for most cases, developers often need more flexibility to create UIs dynamically, using components and directives (often) not known at the time of writing the component that generates this UI. Common use cases include data driven UIs (including forms), A/B experiments, UIs generated via plugin systems, etc.
Angular currently enables dynamic view or template creation only with major drawbacks in two ways:
-
Via the JIT compiler, which can take any string and compile it on the fly within the browser. This approach compromises security of the application (there is a high risk of introducing XSS and compromising the overall security model of Angular) and also comes with a major performance penalty due to the runtime cost of the compilation, and payload size of the overhead of the compiler.
-
Via ViewContainerRef#createComponent and similar APIs, which don't offer enough flexibility to dynamically compose views out of a mixture of static HTML, HTML with dynamically created bindings, components, and directives.
Proposed solution
With Ivy rendering/compilation pipeline being the default and ViewEngine being removed in v13, we can finally start taking advantage of flexibility of Ivy without having to worry about compatibility with ViewEngine, this opens up new possibilities including the follow...
We could introduce a new set of APIs that are built specifically for dynamic view composition. A proper research needs to be conducted to determine the shape of the API, but we can use the following PLACEHOLDER APIs to demonstrate the functionality and serve as a foundation for discussion, brainstorming, and actual API design research...
@Component({
...
template: '<button (click)="renderDynamically()">render</button>'
...
})
class DemoComponent {
constructor(private viewContainerRef: ViewContainerRef) {}
protected async renderDynamically() {
const myCustomView = await createMyCustomView('./myBlue.component',
{userName: 'Kahless', myRoutePath: ['my-route'], showDetails: true});
// appends the view
viewContainerRef.appendEmbeddedView(myCustomView);
}
}Where the templateRef is generated dynamically as follows:
// this doesn't exist yet + API design is to be determined
import {createView, html, component, directive, text, binding, template} from "@angular/core/compose";
import {NgIf} from "@angular/core";
import {RouterLink} from "@angular/router";
import {MyRedComponent} "./myRed.component";
import {MyYellowComponent} "./myYellow.component";
async function createMyCustomView(blueComponentESModulePath, myContext) {
const blueComponent = (await import(blueComponentESModulePath)).default;
// this is where the magic happens
return createView([
html("<div>some static html, that will be automatically serialized by the `createTemplate` call</div>"),
component(MyYellowComponent, { projection: [
text("html string followed by a binding"),
// {{ userName }}
binding(() => myContext.userName),
// you can use javascript expressions instead of `NgIf` to conditionally add view "nodes":
(Math.random() > 0.5) && text(" and followed by another component"),
// <my-red [routeLink]="myRoutePath"></my-red>
component(MyRedComponent, { directives: [
directive(RouterLink , {binding: () => myContext.myRoutePath})
]}),
// but NgIf works as well:
// <p *ngIf="showDetails">Some details</p>
template([
text("some details")
], {directives: [
directive(NgIf, {binding: () => myContext.showDetails})
]})
// NgForOf, NgSwitch, and any custom regular or structural directives would work as well
// TODO: update the proposal with a built-in support for structural directives in `@angular/common`,
// e.g. `ngIfTemplate` - see suggestion from @sg-gdarnell in the comments below.
// TODO: update the proposal with an example of how to use pipes in bindings as requested by @ha100790tag
]})
]);
}How would this be implemented?
Functions template, component, directive, text would be just higher level wrappers around the private Ivy instruction APIs.
Risks & unresolve stuff
There is a lot that needs to be researched in this area to determine the complexity of the implementation and overall viability. The following is an incomplete list of unresolved questions / issues:
- The existing
ViewContainerRefAPIs accept only TemplateRefs or Components and not views directly. Is this a problem? - Do we need to support dynamic template composition (outputting TemplateRef) as well? Or is view composition sufficient?
- Are current Ivy instruction APIs flexible enough to accomodate this feature or do we need to tweak them?
- Can we keep all existing security guarantees to prevent XSS?
- How to attach the new view to the correct injector in the parent?
- Is the existing $localize API sufficient to support localization?
- Should we limit this API just to upcoming "standalone" components, directives, and pipes, or can we make this API work with entities that are part of an NgModule without a major hassle?
- Could this composition API eventually replace the "partial compilation" used to publish Angular libraries? Maybe, it's a bit of a stretch, but it's worth a further exploration...
- and many more...
As a result of these, you can expect major revisions of the proposed solution. The goal of this effort and use-cases this functionality would support should however remain the same.
Are there any trade offs?
Of course, there are always some trade offs.
The main ones that come to my mind:
- We don't plan on supporting templates as strings. Only static html or text (without bindings, Angular components or directives) could be provided as string) — such feature would require the availability of the entire JIT compiler at runtime, which would go against the very core goal of this proposal.
- Performance of creation of dynamically composed views will likely not be as good as that of AOT compiled code. The update performance would be less impacted. There are ways we could improve perf of dynamically created views (e.g. by supporting dynamic template creation), but more research is needed.
- The API is more verbose than the declarative template syntax. Since the goal here is to enable dynamic view creation using imperative JavaScript/TypeScript code, we are trading off some verbosity for flexibility of the imperative coding.
- Limited tree-shaking impact — the higher level API might need to retain a few instructions that would otherwise be tree-shaken away if the template was created using AOT compilation, but the impact should be very limited, especially if each higher level API is a standalone tree-shakable function (as proposed in the example above).
What's the goal of this issue?
The goal is to write down some of the ideas that have been made possible thanks to Ivy and start collecting early feedback that could be used as an input for future RFC.
Alternatives considered
Expose the Ivy instructions as a public API. This has a major drawback that these APIs are low level (not developer friendly) and not stable (it would be hard to evolve the rendering stack if these APIs were public).
Activity
SanderElias commentedon Aug 12, 2021
Question: Isn't it possible to create a small public layer on top of the Ivy instruction set?
This will create a low-level API that still allows evolving the rendering stack, while also providing a flexible basis to build higher-level abstractions.
SanderElias commentedon Aug 12, 2021
Another question: We can already mix-and-match more dynamic templates by using Angular Elements(web components generated by angular).
The current downside of using those is that you can't tell the language server you have those, so you need to turn off most of the syntax checking for templates.
Would fixing that, not already bring a lot of what this RFC is bringing?
SanderElias commentedon Aug 12, 2021
@IgorMinar Thanks for this proposal! It really looks good.
What I'm missing in the createView array, is an option to add a portion using normal template syntax, something like:
Where it uses the same context as the
myContextin your sample for the template.Adding support for "normal" templates will name the use of this API a lot simpler. I know using it will need to ship the full Ivy compiler to the client, but I would like to be able to make that trade-off.
alxhub commentedon Aug 12, 2021
I think that's exactly what this is - it's an API to imperatively construct an Ivy template function, but which doesn't require you to have specific knowledge about how to call the actual template instructions.
I don't think so, because such components still need to be written statically, even if their instantiation is more dynamic. This proposal allows for very dynamic constructions of views, based on runtime data structures.
This is a cool idea, too. One of the concerns here is that it would require some notion of a template scope (what
@NgModuleprovides today for statically compiled components) and that might get very tricky or messy to specify. But it could be done.SanderElias commentedon Aug 12, 2021
@alxhub Thanks for the quick answers! It is good to have this cleared out of the way.
I do like your clarification on how this is a different dynamic as using Angular elements.
This would be the same thing as it is for stand-alone(module-less) components, or am I looking from the wrong side? Those problems need to be solved anyway for truly dynamic components as far as I can see.
alxhub commentedon Aug 12, 2021
Sort of. The problem is that this scope has to be defined at runtime instead of compile time.
One of the challenges here is that Angular actually erases scope information for
NgModules during compilation - this prevents all components/directives/pipes in an application from being referenced byNgModules and thus ineligible for tree-shaking. Having a dynamic, runtime way to specify a compilation scope would require retaining this information across the board, since we can't know ahead of time whichNgModules would be referenced from such a dynamic scope.IgorMinar commentedon Aug 12, 2021
@SanderElias thanks for all the questions. I think @alxhub fielded all/most of them already.
I just want to chime in on:
Dynamic template creation out of templates is something that I'd really like to avoid - it would basically be just a glorified way of using the current JIT compiler in production, which has lots and lots of problems (critical security, performance, and maintenance issues). I have an RFC coming out today, exploring the possibility of eventually removing JIT compilation mode entirely from Angular. I should post it within the next few hours — please stay tuned.
The goal of this proposal is to enable dynamic composition of views in a way that is performant and secure. Many of us would like to have the good old
$compileback from the AngularJS days, and this proposal tries to strike the balance between the flexibility of$compileand security and performance of AOT compilation.39 remaining items
vnesterovsky commentedon Nov 16, 2021
Am I right that current template syntax is not going to be removed in any case in favor of any other template API?
If yes, then having a good intention to enhance existing templates you just add one more API to solve the same task.
Won't it confuse developers more than it is assumed to help?
Besides, in my opinion, current templates are more data driven, which means it's easier to store them, e.g. in database, while composition API is more code driven, which raises questions about how substitutable those two API can be.
gmaggiodev commentedon Nov 16, 2021
View Composition is something that we are waiting since 2016 so this is a great news. But (always there is a "but" we use to say), the flat structure is absolutely not enough for us. I try to explain our project.
We created a UI Framework Platform, based on Angular, that allow Application Developers to create pages using an interactive designer at runtime without the need to code the corresponding components and compile it.
Simplifying a lot to understand the concept:
{ "type": "grid-layout", "items": [ { "type": "card", "properties": { "cols": 4, "title": "Alex Dornick", "subtitle": "Front-End Developer", "imgSrc": "/assets/images/alex.JPG", "imgMode": "avatar" }, "items": [{ "type": "simple-panel", "properties": { "position": "footer" }, "items": [ { "type": "label", "properties": { "repeat": "let i of [1,2,3]", "text": "Label {{i}}" } } ] }] } ] }When a user access to this page...
jeme commentedon Jan 26, 2022
Hello.
Reading thought this as well as reading through all the related topics is a bit concerning to us. We are in the process of evaluating how feasible it is to finally switch from AngularJS to Angular (13 as of this writing).
And we use $compile in the old solution to enable the use of AngularJS Directives/Components in content provided by the users. And so obviously JIT sounds like the thing we are looking for in Angular to replace this, and then finding this is ofc raises quite a big concern for us. (Security is of less concern to us in regards to this as it's a closed of system, but is something in the back of our minds, and I understand the argument, yet it could then be an option that is opt in).
In our case, content is provided by the users via TinyMCE. So the content is provided as HTML as that is what we get out of TinyMCE. The place where AngularJS directives/components come into the picture is with a custom set of plugins to TinyMCE that allows the user to add certain blocks to the source HTML (what he/she is editing) - Once the user submits the content and it's rendered in the client, these custom blocks are actually AngularJS components/directives which are then activated.
Because of this I am having a very hard time wrapping my head around doing the same thing in Angular with the constraints set forth here without a insurmountable amount of trouble. (Essentially having to build our own sort of compiler that translate into the above instructions? that seems like redoing something that is already in Angular after all)
A sandboxed compiler experience would be welcome where it's possible to limit what components, directives, pipes (essentially modules?) that are recognized. But having to use the above "syntax" seems to be a very tough pill for us to swallow with what we know at this point.
torsolaso commentedon Feb 3, 2022
I am interested on this behaviour. It's extremely useful to have the opportunity to draw JSON data in the UI using this feature. When changing from JIT to AOT this feature will disappear? There will be an alternative used by a project for using data inside JSONs and give to the user a friendly interface?
zijianhuang commentedon Mar 22, 2022
The use case is for MailMerge. The frontend app provides some JSON data object, and merge with a HTML template drafted by a computer literate among end users. The merged HTML result will be used as report or Email message. People with skills in MS Word MailMerge should be able to pick up MailMerge based on Angular HTML template.
Therefore, I would expect the design of the API should make it easier for app developers to develop such User Experience for end users.
mrjfalk commentedon Jun 7, 2022
Unfortunately I didn't see the RFC in time (we just started with Angular), but for us the option to compile angular HTML string templates at runtime is very critical to our current application. We have a plugin-like system where we essentially do the following at runtime:
For us this works great and allows building really flexible dynamic plugin UI's. We haven't had any issues with the performance yet, the bundle size is obviously large due to including both the TypeScript and Angular JIT compilers, but the application runs on a local network, so that is not an issue.
MOALANGSVG commentedon Jun 30, 2022
We have an application that must display SVGs (html) that we must interact with click and ngIFs and binging, the SVGs come from the db as a string, their numbers are variable, and since all these SVGs contain the same function (
CloseOpen(){this.condition = !this.condition ; if(this.condition) {this.stats = 'open'}else{this.stats='close'}) with *ngIF='condition' for display inside the SVG a tag) according to the variable 'condition: boolean', we have SVGs with images like: EYE, DOOR, WINDOW…ect each svg contains the two states of the same image ( SVG eye: eye closed and open eye, SVG door: closed door and open door….)Example of the structure of its SVGs:
As mentioned above we don't know how many svgs we have but since they all look alike we chose to create a single component which contains the 'CloseOpen()' function and the 'condition: boolean = true;' variables. and 'stats:string=open;' and to associate the svg that will be associated with this component dynamically as we click on link eye or door , or window… the proper SVG will be associated with this component, so we have a component with differentiate html (Template) associated with it dynamically, with angularjs we do $compile which works well, but since we want to switch to angular the most recent possible (currently 13 or 14) we came across the AOT constraint of ivy the SVG is displayed but there is no compilation or interaction with the dynamically generated SVG, and the API you are citing is not understandable if possible examples on its usage would be a blessing.
vojtechmarek-dev commentedon Mar 27, 2024
As others, I unfortunatelly have missed the RFC.
We are currently upgrading our app from Angular 12 and hit a wall since on 13+ the hybrid AOT+JIT options no longer works.
The concept is important for us because we have templates stored on db, where templates can be configured on gui level and then renedered on demand. This however is probably only 20% of our application, whereas the rest are static components.
We are reluctant give up the benefit of having 80% of our app compiled Ahead Of Time so we are considering staying on old version until this proposed API (or an alternative) is implemented.
However I would like to ask what is the state of this proposal? There has not been any update about this for quite some time.
dennnisk commentedon Apr 9, 2024
We have an ERP software built in Java and AngularJS, which serves as our "BASE," so to speak. It supports dynamic UIs, but through an API, and currently retrieves and compiles HTML/JS.
So, generic business rules belong to the standard project, however, many resources are customized and stored within the client's DB, being loaded into AngularJS (currently) and rendered (HTML, CSS, Javascript, etc). These resources are quite complex objects, sometimes encompassing various components and screens.
The base project was started in 2012/2013, using AngularJS, and we are researching to update the entire frontend structure. While researching how to achieve the same functionality in Angular, I came across this RFC, which, like many, we "missed" because we didn't follow the project so closely.
Anyway, we have something very similar to what mrjfalk has developed.
For us, what JIT allows would be ideal, and since these features will be discontinued in Angular, we are considering 2 hypotheses:
We understand the security issue involved with the use of JIT, but for our reality it permit the flexibility we need.
Anyway, just sharing another case. :)
nikita-fuchs commentedon Aug 1, 2024
I have an application with lots of different form fields defined by components, which have lots of attributes, inputs and outputs. Although I can reuse them in the same component using ng-template, there is no way to reuse them across the 15 other components where I need them. This means I need to copy-paste this part of the template everywhere:
but if I want (input) to do something else, I need to change this on 15 components. Of course I could go ahead and try changing this event's behaviour programatically, but that opens up now issues like scoping etc.
ildarnm commentedon Oct 3, 2024
We have templates that customers can modify. These templates are Angular templates with custom structural directives, custom attribute directives, and interpolation. Because of this, we have to use JIT and include the compiler in the bundle
jame-earnin commentedon Nov 7, 2024
Hello @mgechev
Is there any migration plan or roadmap on imperative & dynamic view creation and Ivy JIT Compiler?