Repository navigation
Conversation
An element's attributes come from three sources: the component's host,
the other directives on the element, and the template. Angular applies
their union for `class`, and lets the last write win for any other
attribute, so conflicting utility classes such as `px-4` from the
template and `px-2` from the component both stay on the element, and
two directives that set `role` or `aria-describedby` overwrite each
other. Attribute resolver bindings, which the compiler emits in the next
change, let an app resolve an attribute of an element from all of its
sources, for example its classes with a resolver such as tailwind-merge.
This commit adds their runtime and public API. Nothing calls the new
`ɵɵattributeResolver(name, handler, flags)` instruction yet, so no app
changes behavior. The specs of the bindings come with the compiler;
this commit's specs cover what an app calls directly: the built-in
resolvers and the provider's rejection of event handler attributes.
When an element registers a resolver for an attribute, the attribute's
bindings record their values instead of writing to the DOM: static
values, `[attr.x]` bindings, and for `class` also `[class]` and
`[class.x]`. Once the view's host bindings have run, the element's
resolvers run from the lowest to the highest priority: the component's
host bindings, the other directives in match order, then the template.
Each receives the values grouped by source, and each later one receives
the previous result folded back into the same groups.
- The grammar of an attribute decides how its sources read and merge.
`class` takes class names and applies the difference between the
classes it applied last and the resolved ones, so classes that other
code added stay on the element. Token lists such as `rel` and
`aria-describedby` take tokens and join them without repeats
(`joinTokens`). Any other attribute takes one value per source and
keeps the last one (`lastValue`).
- `ClassResolveEvent` and `AttributeResolveEvent` carry `sources`, a
`resolver(...extras)` that merges the sources with extra values, and
`resolve(value)` that sets the attribute. Without a call to
`resolve()`, the attribute takes its built-in rule.
- `ResolvedAttribute` is an opaque value that only a bound resolver
creates, so a shorthand can't return plain strings.
- `provideAttributeResolvers({class: twMerge, ...})` sets the resolver
of each attribute, which receives one argument per value. Each
registration looks its resolver up from its element's injector, so a
component can use another one for its own template through
`viewProviders`, and nested calls compose per attribute.
`joinValues(separator)` creates a resolver that keeps repeats.
- A hydrated element starts from the classes that the server rendered,
so the first resolution removes the ones that only the server
resolved. `ComponentFactory` sets whether hydration claimed a root
component's host before it creates the host's directives, and keeps
a component created in a constructor from changing what the code
that creates the outer node reads.
- A translated attribute binding that a resolver reads keeps its value
for the resolver instead of writing it.
- Dev mode reports a misuse of `resolve()`, a foreign result, or a
function value (NG0320), a resolver on `<ng-container>` or
`<ng-template>` (NG0321), a second resolver that a directive inherits
(NG0323), and two directives that set different values for an
attribute that holds one value (NG0324). A `provideAttributeResolvers`
key for an event handler attribute, such as `onclick`, throws.
Change detection, the styling instructions, and `ɵɵattribute` reach the
runtime through hooks that the first registration sets, so an app
without an attribute resolver doesn't bundle it.
The attribute resolver runtime has no syntax yet: nothing emits `ɵɵattributeResolver`, so a template or a host binding can't resolve an attribute of an element from its sources. Compile the two forms of an attribute resolver binding: - `(attr.x)="handler($event)"` receives a resolve event with the values of each source and sets the attribute `x` through it, such as `(attr.class)` for the classes or `(attr.role)` for `role`. - `(class)="F"` is a shorthand for `(attr.class)="$event.resolve((F)($event.resolver))"`, where `F` is a function, or a field that holds one, that receives the resolver. Both compile to `ɵɵattributeResolver` with the attribute's name instead of a listener, in templates and in host bindings, with flags that tell the runtime which form it is. On `<ng-container>` and `<ng-template>` they compile to the same instruction, so the runtime can report them. `(attr.style)` stays an ordinary event binding until style resolvers land. Resolved values are never sanitized, so only attributes whose security context is `NONE` resolve. The template parser reports, as template parse errors (NG5002): - a second resolver of one attribute on one element; - a `(class)` shorthand that is a chain of statements; - an attribute that can't be resolved: a namespaced attribute, an event handler attribute such as `onclick`, or one whose value needs sanitization on that element, such as the `href` of an `<a>`. A host binding doesn't know its element, so a host `(attr.x)` for a namespaced attribute, an event handler attribute, or an attribute whose value needs sanitization on some element, such as `href`, is a host binding parse error (NG5001), in the `host` metadata and through `@HostListener`. JIT compilation throws with the same message. A partial declaration from an older library whose host listens to such an event would compile it as a resolver, so the linker and the JIT facade check the attribute's name there too. A linker that predates attribute resolvers would compile a resolver as a plain listener, so the partial declaration of a component or directive with a resolver in its host or its template requires 22.3.0. An `i18n-attr.x` binding next to an `(attr.x)` resolver marks its translated value as an attribute binding, so the runtime keeps the value for the resolver instead of writing it. A styling spec listened to a directive output named `class` through `(class)`. It now subscribes to the output in code, and still checks that the output emits and that the `[class]` binding applies. BREAKING CHANGE: `(class)` bindings and `(attr.<name>)` bindings for any name other than `style`, in templates, `host` metadata, and `@HostListener`, including the host listeners of partial declarations that the linker or the JIT facade compiles, no longer listen to events or directive outputs with those names. They resolve the attribute of their element instead. To keep an existing listener, rename the output or event together with its handler, or subscribe to the output in code. These bindings are now compile errors: - in a template (NG5002): an `(attr.<name>)` binding for a namespaced attribute, an event handler attribute, or an attribute whose value needs sanitization on its element; a second `(class)` or `(attr.<name>)` binding of one attribute on one element; and a `(class)` binding that is a chain of statements; - in host bindings (NG5001): an `(attr.<name>)` listener for a namespaced attribute, an event handler attribute, or an attribute whose value needs sanitization on some element, such as `(attr.href)`. The linker and the JIT facade reject these host listeners in the partial declaration of a library too. For a resolver that runs more than one statement, bind `(attr.class)` and call `$event.resolve(...)` explicitly, for example `(attr.class)="count(); $event.resolve($event.resolver())"`.
A directive can declare at most one resolver per attribute, and only in
its `host` metadata. Host listeners are keyed by event name, so without
a check a resolver from `@HostListener('class')` would silently replace
one from `host`, or another one from the decorator.
- `@HostListener('class')` and `@HostListener('attr.<name>')` are
errors that point to `host: {'(class)': ...}` instead. An attribute
that can't be resolved at all, such as `href`, keeps the error that
says why.
- A second resolver of one attribute in one `host` object, such as
`(class)` next to `(attr.class)`, is an error.
- A host `(class)` shorthand that is a chain of statements is an error,
as it is in templates; `(attr.class)` still runs statements.
AOT reports these as host binding parse errors (NG5001), and JIT
compilation throws with the same messages. A partial declaration was
checked when its library was compiled, so the linker and the JIT
facade still check only the names of its resolvers' attributes.
BREAKING CHANGE: `@HostListener('class')` and
`@HostListener('attr.<name>')`, for any name other than `style`, are
compile errors (NG5001); JIT compilation throws.
To keep an existing event handler, rename the event and the listener
together, for example `@HostListener('classChange', ['$event'])` with
the code that dispatches the event renamed too, or listen in code
with teardown.
To resolve the host's attribute, bind `(class)` or `(attr.<name>)` in
the `host` metadata instead, for example `host: {'(class)': 'resolve'}`.
In the `host` metadata of a component or directive, a `(class)`
listener that is a chain of statements and a second resolver of one
attribute are compile errors (NG5001) too. Partial declarations, which
the linker and the JIT facade compile, skip these two rules. For a
resolver that runs more than one statement, bind `(attr.class)` and
call `$event.resolve(...)` explicitly, for example
`host: {'(attr.class)': 'count(); $event.resolve($event.resolver())'}`.
Type checking treats attribute resolver bindings as ordinary event bindings: `$event` of `(attr.class)` gets the type of a DOM event, or of a directive output with the binding's name, and a `(class)` shorthand is checked as a handler statement instead of the call that the runtime makes. Check the bindings the way the runtime runs them: - `$event` of an `(attr.x)` binding is the resolve event of its attribute when the types of output events are checked: `ClassResolveEvent` for `class`, and `AttributeResolveEvent` for any other attribute. - A `(class)="F"` shorthand is checked as its expansion, `$event.resolve((F)($event.resolver))`, with `F` checked against `ClassCallback` and the result of the call against `ResolvedAttribute`. A plain call would accept a callback such as `(cn) => 'x'`. The check also infers the parameters of an arrow function and checks the `this` of a method that `F` calls. - A directive output with the name of a resolver binding doesn't claim the binding, which is checked once, as a resolver. - A resolver on `<ng-container>` is an error (NG8121), because the container has no attributes to resolve. Its handler is still checked, with `$event` as `any`. - The `uninvokedFunctionInEventBinding` check (NG8111) no longer reports a `(class)` shorthand, which calls the function it names, nor a resolver on `<ng-container>` or `<ng-template>`, which resolve nothing. It still reports a function that an `(attr.x)` binding names without calling it. - Symbol lookup, which the language service uses, finds the symbols in a shorthand. Also adds the ngtsc specs of the template rules for attribute resolvers (NG5002), whose templates only type-check once the bindings are checked as resolvers. The ngp backend checks attribute resolver bindings differently, so the specs that it fails are listed as its known failures. BREAKING CHANGE: `(class)` and `(attr.<name>)` bindings on `<ng-container>`, for any name other than `style`, are compile errors (NG8121) when templates are type-checked, because the container has no attributes to resolve. Move the binding to an element.
An element's styles come from the same sources as its classes, and an
app can't decide between declarations that compete across them:
Angular's styling priority picks one value per property, so
`padding: 4px` from a component's host and `padding-left: 0` from the
template both apply.
Extend attribute resolvers to the `style` attribute, whose sources are
style declarations: `(style)="F"` is a shorthand for
`(attr.style)="$event.resolve((F)($event.resolver))"`, like `(class)`.
Both compile to `ɵɵattributeResolver('style', ...)`.
At runtime, an element with a style resolver collects one declaration
per property from each source, such as `padding: 4px`: the static
styles of each directive and of the template, its `[style]` and
`[style.x]` bindings, and its `[attr.style]` bindings, which rank after
the source's styling bindings. Angular's styling priority decides each
property, except that a declaration marked `!important` stays over
later ones that aren't. The style bindings no longer write to the
element; `[attr.style]` doesn't replace the whole attribute either.
- The resolved declarations apply in order, as CSS reads them: the last
declaration of a property wins, unless an earlier one is
`!important`. The runtime removes the properties that the previous
result set and this one doesn't, and sets again the later
declarations of a changed shorthand's family, such as `padding-left`
after `padding`, so that the element ends up as the result says. A
table of shorthands links the ones whose longhands have other names,
such as `inset` and `gap`. Properties that outside code set stay.
- Values read the way the `style` attribute reads them, with a small
CSS tokenizer for strings, functions, escapes, comments, and
`!important`. Full CSS syntax isn't modeled.
- `StyleResolveEvent` reads extras and `resolve()` values the way a
`[style]` binding reads them: a string, an array that joins with
`; `, an object map, or a trusted style. Without a call to
`resolve()`, or without an app resolver, `joinDeclarations` joins the
declarations; it's a new experimental API, as are
`StyleBindingValue`, `StyleCallback`, and `BoundStyleResolver`.
- A hydrated element keeps the styles that the server rendered and
that its sources don't name, such as styles that a constructor set,
and the first resolution removes the managed ones that only the
server resolved.
- Resolved styles aren't sanitized, like `[style]` bindings, so `style`
is the only attribute with a security context other than `NONE` that
resolves.
Type checking types `$event` of `(attr.style)` as `StyleResolveEvent`
and checks a `(style)` shorthand against a function of its resolver.
The template and host rules for resolvers apply to `style` too.
BREAKING CHANGE: `(style)` and `(attr.style)` bindings, in templates
and host bindings, no longer listen to events or directive outputs
with those names, and `@HostListener('style')` and
`@HostListener('attr.style')` are compile errors (NG5001).
The bindings resolve the styles of their element instead. To keep an
existing listener, rename the output or event together with its
handler, or subscribe to the output in code.
These bindings are now compile errors too:
- a second `(style)` or `(attr.style)` binding on one element (NG5002)
or in the `host` metadata of one directive (NG5001);
- a `(style)` binding that is a chain of statements, in a template
(NG5002) or in `host` metadata (NG5001);
- a `(style)` or `(attr.style)` binding on `<ng-container>` (NG8121)
when templates are type-checked, because the container has no
attributes to resolve. Move the binding to an element.
For a style resolver that runs more than one statement, bind
`(attr.style)` and call `$event.resolve(...)` explicitly, for example
`(attr.style)="count(); $event.resolve($event.resolver())"`.
Two extended diagnostics warn about bindings that an attribute resolver makes ineffective. - NG8120 (`outputShadowedByAttributeResolver`): a resolver binding, such as `(class)`, `(style)`, or `(attr.role)`, always resolves the attribute of its element, even when a directive on the element has an output of the same name, so the output's events never reach the binding. Code that used such a binding to listen to the output would silently stop receiving its events. The check warns when a resolver binding on a template element shadows a directive output, including one that a host directive exposes under that name. - NG8122 (`propertyBindingBypassesResolver`): a resolver reads static attributes and `[attr.x]` bindings, plus the styling bindings of `class` and `style`, but not property bindings. A `[title]` next to `(attr.title)` still writes the attribute, and its writes can stay in the DOM while the resolved value doesn't change. The check warns when a property binding, an interpolation, an ARIA binding, or a property that maps to the attribute, such as `[className]`, writes an attribute that the element resolves, in the template or in the host bindings of the element's directives, including inherited ones. The checks skip `<ng-container>` and `<ng-template>`, which resolve nothing; type checking already reports a resolver on `<ng-container>` (NG8121). Two type-checking specs that place a resolver next to an output of the same name now suppress the new warning. The ngp backend doesn't run these checks and rejects their names, so the specs that it fails are listed as its known failures.
With attribute resolver bindings alone, an app that wants every
element resolved has to add `(class)` or `(attr.x)` to each one.
`withAutoResolution()`, a feature of `provideAttributeResolvers`,
resolves `class`, `style`, and the attributes that the root call names
on every element that a component or directive matches, without a
binding, including the host of a component created in code and the
component's host directives:
provideAttributeResolvers({class: twMerge, role: lastValue},
withAutoResolution())
- Only the root providers can turn it on, and only their calls list
the attributes it covers, for the whole application. Below the root,
a component turns it off for its template with
`withAutoResolution(false)` and back on with `withAutoResolution()`;
a call without the feature keeps the setting above it and changes
only which resolver runs for an attribute. Nested templates take the
setting of the component that declares them. In dev mode,
`withAutoResolution()` below a root without it throws NG0322; in
production it's ignored.
- An attribute with a resolver binding, such as `(class)` or
`(attr.role)`, is resolved only through its bindings.
- An attribute whose value is a URL, HTML, or a script on an element,
such as the `href` of an `<a>`, isn't resolved on that element, and
neither is an event handler or a namespaced attribute. The check
reads the element's tag and namespace, including for a host created
in code.
- The setting is looked up once per component view and root view. Each
element remembers the values of each source and calls the resolver
again only when they change.
- Where the feature is off, the attribute's bindings apply as they do
without it.
- A component whose template was first created before a root listed an
attribute keeps rendering without resolving it, because the
template's setup is cached when it's first created. Apps declare the
feature in the root providers, which run before any template
renders; a test suite that turns it on partway can hit this.
Element creation and `ComponentFactory` call a third hook after they
create an element's directives. It stays unset until
`withAutoResolution()` runs, so an app that doesn't use the feature
doesn't bundle it. The feature turns on for the whole process, so its
specs run in their own targets.
Attribute resolvers have no guide on angular.dev yet: the API reference and the NG8120 and NG8122 pages describe single pieces, but not how an app provides resolvers, binds them in templates and hosts, or turns on automatic resolution. Add a guide page under Components, after Host elements, that covers the problem, the built-in rules, the `(class)` and `(style)` shorthands and the `(attr.x)` form, host bindings, where a provider applies, automatic resolution and when names enroll, which attributes can't be resolved, and the main limits. Link it from the binding collisions section of the host elements guide, the styling guide, and both diagnostic pages.
|
More context for reviewers: the description of #67519 is now the full feature reference for this PR. It links to the design decisions and the alternatives that lost (Flarette#10), the measurements of today's behavior (Flarette#7), the feature's cost (Flarette#8), and the error conditions and tests (Flarette#9). |
bec57c1 to
b36771a
Compare
|
We appreciate the effort and interest here, but this doesn't align with the direction we want Angular to go. Aside from that, we largely avoid making things like this configurable because it makes it really hard to understand components behavior if the behavior is hidden behind a bunch of configurable knobs you cannot see by looking at the component at a quick glance. Anything that makes it harder for humans to reason about what a component does also makes it harder for AI agents to reason about, too. Thank you, again, though, for your effort and contribution. |
Proposal: #67519
When a component, its other directives, and the template all set one attribute on an element,
Angular keeps whichever write comes last: a directive's
[attr.role]overwrites the template'sstatic
role, and conflicting utility classes such aspx-4andpx-2both stay. This PR lets anapp decide: a resolver binding,
(attr.x), or the(class)and(style)shorthands, receives everysource of the attribute in priority order and resolves them into one value, with a resolver that
the app provides per attribute name.
What it looks like
With
withAutoResolution()in the root providers, every element that a component or directivematches resolves its enrolled attributes without a binding.
How it runs
Four grammars decide how sources are read and applied: class lists (
class), declarations(
style), token lists (rel,aria-describedby, and similar), and scalars (every other name).Built-in rules:
lastValue,joinTokens,joinDeclarations, andjoinValues(separator).Attributes whose value needs sanitization (
href,srcon most elements,on*, namespaced names)can't be resolved: a compile error in templates and host bindings, and skipped per element by
automatic resolution.
New public API (`@angular/core`, all `@experimental 22.3`)
provideAttributeResolvers(resolvers, ...features),withAutoResolution(enabled?)lastValue,joinTokens,joinDeclarations,joinValuesAttributeResolver,ClassResolver,AttributeResolverFeatureAttributeResolveEvent,ClassResolveEvent,StyleResolveEvent,AttributeSources,ClassSources,ResolvedAttributeAttributeValue,ClassBindingValue,StyleBindingValue,BoundClassResolver,BoundStyleResolver,ClassCallback,StyleCallbackRuntime codes
NG0320–NG0324; compiler codesNG8120(outputShadowedByAttributeResolver),NG8121, andNG8122(propertyBindingBypassesResolver).Commits: review one at a time; before the rebase onto the current main, each built and passed its own targets
feat(core): add an attribute resolver runtime: the instruction, per-element data, the class,token-list, and scalar grammars,
provideAttributeResolvers, the hooks. Nothing emits theinstruction yet; its direct API specs run in a core-only target.
feat(compiler): compile attribute resolver bindings: the classifier, the template pipeline andi18n lowering, the host security exclusion, the
22.3.0partialminVersion, the acceptance andSSR specs.
BREAKING CHANGEfor listeners namedclassandattr.x.feat(compiler-cli): validate attribute resolver host bindings: the host declaration rules andthe
@HostListenererrors.BREAKING CHANGEfor@HostListener.feat(compiler-cli): type-check attribute resolver bindings:$eventper grammar, the shorthandchecks,
NG8121.BREAKING CHANGEfor<ng-container>.feat(core): resolve styles with a style resolver: the declarations grammar, the shorthand table,the per-property diff,
(style)and(attr.style)across compiler, type checker, and runtime.BREAKING CHANGEfor style listeners.feat(compiler-cli): add attribute resolver diagnostics:NG8120,NG8122, and their guidepages.
feat(core): resolve attributes automatically:withAutoResolution()andNG0322.docs: add an attribute resolver guide: the angular.dev guide page, its navigation entry, andlinks from the host elements, styling,
NG8120, andNG8122pages.Evidence
<li menuItem role="separator">with a directive's[attr.role]="'menuitem'"rendersrole="menuitem". After: with(attr.role)="$event.resolve($event.resolver())", it rendersrole="separator".<ui-button class="px-2">withhost: {class: 'px-4 py-2'}rendersclass="px-4 py-2 px-2". After: withprovideAttributeResolvers({class: twMerge})and a host(class), it rendersclass="py-2 px-2".Tests and cost
All pass on the last commit, on
mainatd5b60537e1. Before that rebase, each commit passed its own targets.//packages/core/test/acceptance/attribute_resolver:attribute_resolver(Domino)//packages/core/test/acceptance/attribute_resolver:attribute_resolver_web_chromium//packages/core/test/acceptance/attribute_resolver:auto_resolution,--runs_per_test=10//packages/core/test/acceptance:acceptance//packages/platform-server/test:test, with the hydration specs//packages/platform-server/test:attribute_resolver_auto_hydration_test, 10 runs//packages/compiler-cli/test/ngtsc:ngtsc//packages/compiler-cli/test/ngtsc:ngtsc_ngp//packages/compiler-cli/src/ngtsc/typecheck/test:test//packages/compiler/test:test, with the type-check block specs that moved therefull,linked,declaration-only,codegen, withr3_view_compiler_attribute_resolversymbol_testsCost per element, measured before the last performance change (static styles parsed once,
source-free elements skipped), so the refresh figures are upper bounds. JIT dev mode, Domino,
N=1000, extra µs over plain Angular:
classclassclassrolestyleIn the measured example app, a single
(attr.role)binding added about 7.1 kB gzip; apps thatdon't use the feature pay null checks in three hooks. Automatic resolution takes five
LViewslotsfor each enrolled name that can be resolved on an element a directive matches, unless the element
already resolves that name with a binding.
Merge Danger
Door: one-way
(class),(style), and every(attr.x)become reserved binding names with new public API.Removing them later breaks apps and libraries that adopt them, and partial declarations that use
them require a
22.3.0linker.Blast Radius: templates
Who is affected
class,style, orattr.xthroughthose bindings change behavior; see the breaking changes below.
creation.
ComponentFactory.createreads a root host's hydration information before its directives run.That path runs for every hydrated app.
Known limits, documented
Syntax; importance between a shorthand and its longhands isn't modeled.
[style]map key stays.NG8122matches attribute names in lowercase and doesn't follow value aliases of a base class.name registry lives for the process.
throws there; built-in rules read arrays.
resolve()becomes its source text; dev mode throwsNG0320.ngpbackend doesn't run the resolver host checks, type checks, or extended diagnostics; thosespecs are on its known-failures list.
PR Checklist
PR Type
What is the current behavior?
When several sources set one attribute on an element, the last write wins (
classandstyletakethe union). Apps can't resolve conflicts such as
px-4andpx-2, or keep a template'sroleovera directive's binding.
Issue Number: #67519
What is the new behavior?
provideAttributeResolvers(map, ...features)registers a resolver per attribute name for theelement injectors below it; each name is looked up separately. Without one, a built-in rule applies.
(attr.x)="handler($event)"receives the attribute's event: the collectedsources, the boundresolver(...extras), andresolve(value).(class)and(style)are shorthands that take acallback. Without a
resolve()call, the built-in rule applies.the previous result folded into the sources.
withAutoResolution()in the root providers resolves enrolled names on every element that acomponent or directive matches;
withAutoResolution(false)turns it off for a subtree.reconciliation and serialization limits.
Does this PR introduce a breaking change?
Yes
No
(class),(style), and(attr.<name>)bindings, in templates,hostmetadata, and partialdeclarations, no longer listen to events or outputs with those names; they resolve the attribute.
With strict templates,
NG8120warns for a same-named directive output. Migration: rename the output or event with its handler, or subscribe in code.@HostListener('class'),@HostListener('style'), and@HostListener('attr.<name>')are compileerrors (
NG5001). Migration: bind the resolver inhost, or rename the event.Compile errors: an
(attr.<name>)for a namespaced, event-handler, or sanitized attribute; a secondresolver of one attribute on one element or in one
host; a shorthand that is a chain ofstatements (use
(attr.class)with$event.resolve(...)); a resolver on<ng-container>(
NG8121).Other information
A guide page,
guide/components/attribute-resolvers, comes with the PR; theNG8120andNG8122pages come with commit 6.