Skip to content

feat(core): resolve element classes with a (class) binding - #5

Open
Flarette wants to merge 6 commits into
mainfrom
feat/class-resolver-pr
Open

Flarette wants to merge 6 commits into
mainfrom
feat/class-resolver-pr

Conversation

@Flarette

@Flarette Flarette commented Nov 8, 2026 •

Copy link
Copy Markdown
Owner

Proposal: angular/angular#71888 | Feature reference | Design record | Rounds | Deferred

Why the change

Angular applies the union of the classes that an element gets from its component, its other directives, and its template, so conflicting utility classes such as px-4 and px-2 both stay; this branch is the reference implementation of the (class) binding and provideClassResolver() proposed in angular#71888, and this description records how the design got there.

Special things to note

  • This PR is a reference, not a merge candidate. It's based on upstream main at 5ac4cf7b54. An upstream PR waits until the team responds to the issue.
  • It has breaking changes. (class) and (attr.class) become reserved: a template no longer listens to an output named class through them (NG8120 warns; rename the output), @HostListener('class') is a compile error (bind (class) in host instead), and a partial declaration that uses them needs a 22.3.0 linker.
  • Apps that don't use the feature still run changed code. ComponentFactory.create now reads a root host's hydration information before its directives run, and restores the wasLastNodeCreated flag around nested component creation, on every hydrated app. Every app also pays a null check per view refresh, per element that hosts a directive at creation, and per class binding in a template's first pass.

Change outline

The issue shows the API. This outline shows how it's built, how the design got there, and what's still open.

What runs per element

On each refresh of a view, for each element with a resolver:

refreshView
  _refreshClassResolvers(lView)                      # null unless an app uses the feature
    collectClassSources(element)                     # [component, directives, template]
    for each registration, from the lowest priority  # component host, directive hosts, template
      handler($event: ClassResolveEvent)
        (class)="F"  →  $event.resolve((F)($event.resolver))
          cn(...extras)                              # extras rank at the end of the caller's source
            resolver(componentStr, directivesStr, templateStr)   # from provideClassResolver()
      foldClassNames(result) → sources for the next registration
    applyResolvedClasses(element)                    # diff against the last result; other classes stay

The types

All new public API in @angular/core is @experimental 22.3.

// One list of class names per source, lowest priority first. Directives share one slot.
type ClassSources = readonly [
  component: readonly string[],
  directives: readonly string[],
  template: readonly string[],
];

// What provideClassResolver() takes. twMerge, shadcn's cn, and clsx fit unchanged.
type ClassResolver = (...classes: string[]) => string;

// $event of the full form, (attr.class).
interface ClassResolveEvent {
  readonly sources: ClassSources;
  resolver(...extras: ClassBindingValue[]): ResolvedClasses; // the app's resolver, bound to the sources
  resolve(classes: ClassBindingValue | ResolvedClasses): void; // without a call, the sources stay
}

// The shorthand: (class)="F" means (attr.class)="$event.resolve((F)($event.resolver))".
type ClassCallback = (cn: BoundClassResolver) => ResolvedClasses;

// A type-only brand. Only a bound resolver creates one, and dev mode checks where it came from.
interface ResolvedClasses {
  readonly [ɵRESOLVED_CLASSES_BRAND]: true;
}

Where the code lives

packages/core/src/render3/
├── instructions/class_resolver.ts       # ɵɵclassResolver, the event, the fold, the diff
├── instructions/class_resolver_hook.ts  # three hooks, so apps without the feature tree-shake it
├── class_resolver_provider.ts           # provideClassResolver()
└── class_resolver_auto.ts               # withAutoResolution()
packages/compiler/src/
├── render3/r3_class_resolver.ts         # one classifier for (class) and (attr.class)
├── template/pipeline/                   # emits ɵɵclassResolver(handler, flags)
└── typecheck/ops/events.ts              # $event: ClassResolveEvent, the shorthand's checks
packages/compiler-cli/src/ngtsc/         # NG8120, NG8121, host rules, partial minVersion 22.3.0

Commits and their tests

c6cb8fde74  feat(core): add a class resolver runtime
            runtime, provideClassResolver(), the hooks, the bundling goldens
            no specs yet: nothing emits ɵɵclassResolver
ec9151bfd8  feat(compiler): compile class resolver bindings              BREAKING: outputs named class
            compliance 11 full and 9 linked, class_resolver 98, SSR and hydration
            rewrites the angular/angular#71661 spec that listened to an output named class
ed02b6ac19  feat(compiler-cli): validate class resolver host bindings    BREAKING: @HostListener('class')
            host rules, @HostListener errors, minVersion 22.3.0
5d263ff1d9  feat(compiler-cli): type-check class resolver bindings
            $event, the shorthand's checks, NG8121, the NG8111 exemption
50b54c4fc3  feat(compiler-cli): add the outputShadowedByClassResolver check
            NG8120 and its guide page
4896eeee2d  feat(core): resolve classes automatically
            withAutoResolution(), NG0322, auto_resolution 18 (10 of 10 runs)

last commit, full set: acceptance 2724, platform-server 420, ngtsc 7222, typecheck 1741, preprocessor 1651

How the design got there

The design went through two design rounds and an upstream-preparation round. docs/rounds.md records the design rounds, and proposal.md has every measurement.

Round 1, 2026-10-17 to 10-26: from one winner to a fold

In the first prototype, a handler returned the classes, (class)="cn($event)", and $event was the ClassSources tuple. Each registration replaced the previous one:

 <ui-button tone class="px-2" (class)="cn($event)" />
- the last registration wins             # a library's resolver and its state classes vanish
- among directives, imports order wins   # consumers rarely think about it
- $event.inherited(Directive)            # delegation by name depends on match order
+ every resolver runs, lowest priority first
+ each gets the previous result back in its sources, folded by origin

The sources are ordered by source, not by kind (static before bound). The case that decided it is a component with computed variants and a consumer with a static override. The component's host binds [class]="variants()", which is 'inline-flex h-9 px-4 bg-primary', and the consumer writes <ui-button class="px-2 w-full">.

Ordered by kind, the consumer's static classes rank below the component's bound ones:

cn([[], [], ['px-2', 'w-full']], [['inline-flex', 'h-9', 'px-4', 'bg-primary'], [], []]);
// 'w-full inline-flex h-9 px-4 bg-primary': the consumer's px-2 is lost

Ordered by source, the template ranks above the component:

twMerge('inline-flex h-9 px-4 bg-primary', '', 'px-2 w-full');
// 'inline-flex h-9 bg-primary px-2 w-full'

Ordering by source also matches what Angular already does for one class name (style_binding_list.ts), so (class) doesn't change which plain classes render.

The round also found the following:

Round 2, 2026-10-26 to 10-31: resolve() instead of a return value

Returning the classes broke an event binding's void contract. The value wasn't type-checked, and a later statement in the handler could replace it silently. NG8111 had to exempt every (class), every bundle carried about 26 resolver symbols, and people and coding agents would forget a per-element (class).

- <ui-button (class)="cn($event)" />                       # the return value is the classes, unchecked
+ <ui-button (class)="(cn) => cn('shadow-lg')" />          # must return the ResolvedClasses that cn creates
+ <ui-button (attr.class)="$event.resolve(classes)" />     # the full form; without resolve(), the sources stay

A component's extras rank at the end of its own source, not after every source. This was measured with clsx 2.1.1 and tailwind-merge 3.7.0, simulating the fold, with host: {class: 'inline-flex px-4'} and a consumer's class="bg-red-600" (class)="(cn) => cn('shadow-lg')":

The host adds bg-muted Element
After the sources: [$event, 'bg-muted'] inline-flex px-4 bg-muted shadow-lg: the consumer's color is lost
Before the sources: ['bg-muted', $event] inline-flex px-4 bg-red-600 shadow-lg
In its own source: cn('bg-muted') inline-flex px-4 bg-red-600 shadow-lg

The round decided the following, with the reason for each:

Decision Why
The resolver takes strings and returns a string A resolver typed through declaration merging fails with TS2717 when a library augments the type differently. A resolver that receives [class] values fails twMerge's types, and clsx(new Set(['a'])) returns '' (measured). Angular normalizes extras the way it reads [class], so false adds nothing instead of rendering a class named false.
(class) shadows an output named class, and NG8120 warns Round 1 fell back to listening, with a runtime warning. Shadowing matches how an output shadows a native event, and the compiler can report it.
@HostListener can't declare a resolver A decorator always calls its method, so it can't pass the shorthand's callback. A method that returned classes would compile and silently do nothing. The guide already prefers host.
One resolver per directive, and an inherited second one throws NG0323 twMerge resolves by position, and two resolvers in one directive would run in an order nobody writes down. A library's .d.ts carries no host bindings, so the check runs at runtime.
NG8121 and NG0321 for (class) on containers They're there in case the generic check for bindings that do nothing on containers never lands upstream.
The runtime sits behind three hooks An app without the feature carries only the hook symbols. The eight bundling symbol tests guard it.
withAutoResolution() is declared in the root providers only See the first row of the constraints below.
A shorthand is type-checked as the call that runs The audit found that (class)="active ? first : classes" dropped a method's this, compiled, and crashed. Exact checking can report up to three errors on one wrong callback.

Designs that lost to the shorthand and resolve():

Design Why it lost
A callable event: (class)="$event('x')" The same ranking, but $event becomes a function. The callback names the resolver as a parameter, and a component can bind it by reference.
Sugar over an array: (class)="[$event, 'x']" $event would mean the sources in the shorthand and the event in the full form. Extras rank by position, so a host that appends drops the consumer's class. (class)="'x'" replaces every class without a warning.
resolve() applies the app's resolver itself The full form would lose its guarantee that nothing happens unless the handler writes it, and would need a flag to opt out.
A branded string instead of ResolvedClasses Checked at compile time only. A cast or $any passes without a warning.
Throw when no resolver is registered (class) would need a provider before an app could adopt it. The plain merge matches what Angular renders today.
Ban [class] next to (class) Static class, [class.x], and host bindings stay sources anyway, and adopting (class) would mean rewriting existing [class] bindings.

So both stay allowed, and they differ:

Case [class]="v" and cn() cn(v)
A top-level false Asserts in dev mode, and the resolver doesn't run Adds nothing
Rank within the source Before the source's [class.x] bindings After them, at the end of the source
A component with a class input The input takes the value Reaches the element
Type checking Only the expression; the type-check block skips class bindings Checked against ClassBindingValue
Visible to a lower resolver, such as a host's Yes No; it exists from the caller's level up

Round 3, 2026-11-06 to 11-08: preparing for upstream

An external review (Codex) checked each step: the code cleanup (R1), the test audit (R2), and the rebuilt history (R3).

  • R1, code style: naming, comments, and structure only, in Angular's style. Read-only probes compared the classifier, the NG8120 guard, the merge, and the class diff before and after, and found no behavior change. The commented-out reservation of other (attr.*) names was removed.
  • R2, test audit: the audit kept one spec per behavior, at the layer that owns it, plus every spec for an earlier bug, an audit finding, or an error code. It deleted 31 specs. For each error code, a probe disabled the check and showed that a remaining spec fails. One merged table had lost a DOM assertion, so it checks the DOM again.
  • R3, history: six commits on upstream main. The compiler-first order wasn't bisectable, because it emitted ɵɵclassResolver before core exported it, so the runtime now comes first.

Constraints that shaped it

Constraint What it forced
Angular builds an element's resolver data once per template, in the first creation pass, while providers resolve per instance A lower provider would make the result depend on load order: a <ui-card> first rendered in the app shell would stay unresolved inside a lazy /dashboard that turns the feature on. So withAutoResolution() is root-only (NG0322), and a template compiled before the first call never gets it.
A library's .d.ts records no host bindings An inherited second resolver can only be caught at runtime (NG0323).
The app's linker compiles a library's partial declarations minVersion: "22.3.0" for declarations that use the binding.
A [class] value is stored as a list sorted by class name Conflicts inside one [class] value resolve alphabetically. Extras keep their order, so cn(value) resolves in the order written.
An input named or aliased class takes the template's [class], as in spartan-ng That binding isn't a source. The template's static class still is.
The Rust preprocessor doesn't take outside contributions It isn't changed. It reuses @angular/compiler, so (class) compiles there, but it doesn't run the host rules or NG8120.
Upstream drops type errors that start at a template arrow parameter (class)="(cn) => () => cn()" compiles until angular#71734 lands.

Properties of the prototype

  • Classes that something else adds, such as Renderer2.addClass() or an animation, stay on the element. The resolver doesn't see them.
  • Without a provider, Angular applies a plain merge, which renders what Angular renders today.
  • Server rendering and hydration produce the same classes as the browser. When hydration claims an element, the first resolution starts from its static classes, or from the classes in the DOM when it has none, and removes classes that only the server resolved.
  • An explicit (class) runs on every refresh of the view that declares it, because its callback can read other state. Automatic resolution skips the resolver when no source's string changed.
  • Each source's static classes are computed once per template. The merged static string is still written at creation, so a directive's constructor sees the same classList as today.
  • The checkNoChanges pass doesn't run the handlers.

Angular's own cost per element, measured in JIT dev mode with Domino and the resolver stubbed out, N=1000:

Setup Creation Refresh, no change Refresh, one class changed
Baseline, no resolver 3.2–3.3 µs 0.045 µs 0.50–0.52 µs
Explicit (class) +2.2 µs +1.4–1.5 µs +1.6–1.7 µs
Automatic resolution +1.1 µs +0.26 µs +1.25 µs
Automatic resolution turned off for a subtree ~0 +0.007 µs ~0

twMerge adds 0.03–0.04 µs per call when its cache has the input, and 0.7–2.4 µs when it doesn't. Production mode, AOT, and a real browser aren't measured.

Deferred and known gaps

Options for the team to decide, from the design record:

  • Templates compiled before withAutoResolution(): warn once in dev mode, drop the cached template data, or set the data up lazily. Lazy setup would also let any provider turn the feature on. (Relevant on text fixtures that cache templates, not breaking but can introduce a footgun)
  • Duplicate type errors: deduplicating diagnostics after type checking could report one error for a wrong callback instead of three.
  • The (attr.*) namespace isn't reserved. Other names stay ordinary event bindings.
  • [class] asserts on a top-level false in dev mode, while extras accept it.

Known gaps, listed in docs/DEFERRED.md:

  • A directive constructor that calls createEmbeddedView() overwrites the hydration flag, so its element can keep classes that only the server resolved.
  • With legacy optional chaining, (class)="choice?.classes" calls the method without this.
  • Type checking doesn't visit bindings on <ng-template> (upstream), so only the runtime NG0321 reports one.
  • ngp can widen an error span inside a shorthand, and its test driver can't detect a lost mapping.
  • Two rejection specs wait for fix(compiler): report errors at arrow parameters angular/angular#71734.

Left out on purpose:

  • Resolvers for other attributes and a (style) counterpart: each attribute needs its own source shape and fold rule.
  • Automatic resolution for elements that no component or directive matches: such an element has one source, so nothing can conflict. A component can expose cn and bind [class] instead.
  • A [static, bound] split per source, and a switch that makes one resolver replace the lower ones: no case needs them yet.
An element's classes come from three sources: the component's host,
the other directives on the element, and the template. Angular applies
their union, so conflicting utility classes such as `px-4` from the
template and `px-2` from the component both stay on the element, and
the stylesheet decides which one wins. Class resolver bindings, which
the compiler emits in the next change, let an app resolve the classes
of an element with a resolver such as tailwind-merge.

This commit adds their runtime and public API. Nothing calls the new
`ɵɵclassResolver` instruction yet, so no app changes behavior.

When an element registers a resolver, its class bindings record their
values instead of writing to the DOM. 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 classes grouped by
source in `ClassSources`, and each later one receives the previous
result folded back into the same groups. The runtime then applies the
difference between the classes it applied last and the resolved ones,
so classes that other code added, such as through
`Renderer2.addClass`, stay on the element.

- `ClassResolveEvent` carries `sources`, a `resolver(...extras)` that
  merges the sources with extra classes, and `resolve(classes)` that
  sets the element's classes. Without a call to `resolve()`, the
  classes pass through unchanged.
- `ResolvedClasses` is an opaque value that only a bound resolver
  creates, so a `(class)` shorthand can't return plain strings.
- `provideClassResolver(resolver)` sets the function that merges the
  classes. Each registration looks it up from its element's injector,
  so a component can use another one for its own template through
  `viewProviders`. Without a provider, the merge flattens the sources
  and drops repeated names.
- 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.
- Dev mode reports a misuse of `resolve()` and a foreign shorthand
  result (NG0320), a resolver on `<ng-container>` or `<ng-template>`
  (NG0321), and a second resolver that a directive inherits (NG0323).

Change detection and the styling instructions reach the runtime
through hooks that the first registration sets, so an app without a
class resolver doesn't bundle it.
Compile the two forms of a class resolver binding, which resolve the
classes of an element through the class resolver runtime:

- `(attr.class)="handler($event)"` receives a `ClassResolveEvent` with
  the classes of each source and sets the element's classes through
  it.
- `(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 `ɵɵclassResolver` 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. Other `attr.*` event
names stay ordinary event bindings.

The template parser reports a second class resolver on one element,
and a `(class)` shorthand that is a chain of statements, as template
parse errors (NG5002).

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)` and `(attr.class)` bindings, in templates
and host bindings, no longer listen to events or directive outputs
with those names.

They resolve the classes of their element instead. To keep listening,
rename the output or event together with its listener, or subscribe
to the output in code.
A directive can declare at most one class resolver, 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.class')` are
  errors that point to `host: {'(class)': ...}` instead.
- `(class)` and `(attr.class)` in one `host` object are 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 linker that predates class resolvers would compile one as a plain
listener, so the partial declaration of a component or directive with
a class resolver in its host or its template now requires 22.3.0.

BREAKING CHANGE: `@HostListener('class')` and
`@HostListener('attr.class')` are compile errors.

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 classes, bind `(class)` or `(attr.class)` in the
`host` metadata instead, for example `host: {'(class)': 'resolve'}`.
Type checking now checks class resolver bindings the way the runtime
runs them.

- `$event` of an `(attr.class)` binding is a `ClassResolveEvent` when
  the types of output events are checked.
- 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
  `ResolvedClasses`. 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 named `class` or `attr.class` doesn't claim the
  binding, which is checked once, as a resolver.
- A class resolver on `<ng-container>` is an error (NG8121), because
  the container has no classes 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 class resolver on a container, which NG8121 reports.
- Symbol lookup, which the language service uses, finds the symbols
  in a shorthand.

Also adds the ngtsc specs of the template rules for class resolvers
(NG5002), whose templates only type-check once the bindings are
checked as resolvers.

The ngp backend checks class resolver bindings differently, so the
specs that it fails are listed as its known failures.
`(class)` and `(attr.class)` always resolve the classes of their
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 `(class)` to listen to such an output would silently stop
receiving its events.

The new extended diagnostic NG8120 (`outputShadowedByClassResolver`)
warns when a class resolver binding on a template element shadows a
directive output named `class` or `attr.class`, including one that a
host directive exposes under that name. `<ng-container>` and
`<ng-template>` resolve no classes, and type checking already reports
a resolver on them (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
this check, so the specs that it fails are listed as its known
failures.
With class resolver bindings alone, an app that wants every element
resolved has to add `(class)` to each one. `withAutoResolution()`, a
feature of `provideClassResolver`, resolves 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:

    provideClassResolver(twMerge, withAutoResolution())

- Only the root providers can turn it on. Below the root, a component
  turns it off for its template by providing the resolver without the
  feature, and back on by providing it with the feature; nested
  templates take the setting of the component that declares them. In
  dev mode, a provider below a root without the feature throws NG0322;
  in production it's ignored.
- An element with a `(class)` or `(attr.class)` binding is resolved
  only through its bindings.
- The setting is looked up once per component view and root view. Each
  element remembers the classes of each source and calls the resolver
  again only when they change.
- Where the feature is off, class bindings apply as they do without
  it.
- A component whose template was first created before
  `withAutoResolution()` ran keeps rendering without automatic
  resolution, 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant