Title: [Feature Request] Provide ability to specify class resolution logic at component's host when supplied by multiple sources. · Issue #67519 · angular/angular · GitHub
Open Graph Title: [Feature Request] Provide ability to specify class resolution logic at component's host when supplied by multiple sources. · Issue #67519 · angular/angular
X Title: [Feature Request] Provide ability to specify class resolution logic at component's host when supplied by multiple sources. · Issue #67519 · angular/angular
Description: Attribute resolvers NoteImplemented in #71966. This description is the feature reference. Why it works this way: Flarette#10, design decisions and the alternatives that lost. Numbers: Flarette#7, today's behavior, measured, and Flarette#...
Open Graph Description: Attribute resolvers NoteImplemented in #71966. This description is the feature reference. Why it works this way: Flarette#10, design decisions and the alternatives that lost. Numbers: Flarette#7, t...
X Description: Attribute resolvers NoteImplemented in #71966. This description is the feature reference. Why it works this way: Flarette#10, design decisions and the alternatives that lost. Numbers: Flarette#7, t...
Opengraph URL: https://github.com/angular/angular/issues/67519
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"[Feature Request] Provide ability to specify class resolution logic at component's host when supplied by multiple sources.","articleBody":"# Attribute resolvers\n\n> [!NOTE]\n> Implemented in #71966. This description is the feature reference. Why it works this way: Flarette/angular#10, design decisions and the alternatives that lost. Numbers: Flarette/angular#7, today's behavior, measured, and Flarette/angular#8, the feature's cost. Error conditions and tests: Flarette/angular#9.\n\nAn attribute resolver decides the value of one attribute of an element when several sources set\nit: the component on the element, its other directives, and the template. Angular collects the\nvalue that each source gives, merges the values with the attribute's resolver, and applies the\nresult.\n\nWithout a resolver, this directive's `[attr.role]` binding overwrites the template's static `role`:\n\n```ts\n@Directive({selector: '[menuItem]', host: {'[attr.role]': 'role()'}})\nexport class MenuItem {\n readonly role = signal('menuitem');\n}\n```\n\n```html\n\u003cli menuItem role=\"separator\">\u003c/li>\n```\n\n```html\n\u003cli menuitem=\"\" role=\"menuitem\">\u003c/li>\n```\n\nWith an `(attr.role)` binding, the template's value wins, because the template has the highest\npriority:\n\n```html\n\u003cli menuItem role=\"separator\" (attr.role)=\"$event.resolve($event.resolver())\">\u003c/li>\n```\n\n```html\n\u003cli menuitem=\"\" role=\"separator\">\u003c/li>\n```\n\nYou can resolve any attribute that doesn't need sanitization:\n\n- `(attr.x)` resolves the attribute `x`. It's the full form, and it works for every name that Angular can resolve. See [Names](#names).\n- `(class)` and `(style)` are shorthands for `(attr.class)` and `(attr.style)`.\n- With [automatic resolution](#resolve-every-element-automatically), you don't write the binding:\n Angular resolves `class`, `style`, and the attributes that you list on every element that a\n component or directive matches.\n\nThe typical use for `class` is Tailwind CSS. Conflicting utilities, such as `px-4` from the\ncomponent and `px-2` from the template, then resolve by the priority of the source that set them,\nnot by the order of rules in the stylesheet.\n\n## Provide resolvers\n\n`provideAttributeResolvers(resolvers, ...features)` registers the function that merges each\nattribute:\n\n```ts\nimport {joinValues, provideAttributeResolvers} from '@angular/core';\nimport {bootstrapApplication} from '@angular/platform-browser';\nimport {twMerge} from 'tailwind-merge';\n\nbootstrapApplication(App, {\n providers: [provideAttributeResolvers({class: twMerge, 'data-labels': joinValues(', ')})],\n});\n```\n\nThe map's keys are attribute names. The value of `class` is a `ClassResolver`, and the value of\nany other name is an `AttributeResolver`:\n\n```ts\ntype ClassResolver = (...classes: string[]) => string;\ntype AttributeResolver = (...values: string[]) => string | null;\n```\n\n- Angular calls a resolver with one argument per entry, from the lowest to the highest priority:\n one per class for `class`, one per declaration for `style`, one per token for a token list, and\n one per contributor for any other attribute. See [Grammars](#grammars).\n- Extras that a binding adds come right after the entries of the binding's own source.\n- For `class`, Angular splits the returned string on whitespace and drops empty and repeated\n names.\n- For a scalar attribute, `null` removes the attribute. For a token list, `''` removes it too.\n- For `style`, a `null` result removes the declarations that the resolver manages: those it set\n before, or on the first resolution the element's static styles and, on a hydrated element, the\n properties its sources name. Other declarations stay, unless removing a managed shorthand removes\n them too. Angular doesn't remove the `style` attribute itself.\n\nFor example, with a component whose host has `class=\"px-4 py-2\"`:\n\n```html\n\u003cui-card class=\"px-2\" (class)=\"(cn) => cn()\" />\n```\n\n```text\nresolver arguments: 'px-4', 'py-2', 'px-2'\n```\n\nWith `twMerge`, the element gets the classes `py-2 px-2`. An empty `class` attribute adds no\nargument.\n\nA shadcn-style `cn` fits the `class` contract too:\n\n```ts\nimport {clsx, type ClassValue} from 'clsx';\nimport {twMerge} from 'tailwind-merge';\n\nexport function cn(...inputs: ClassValue[]): string {\n return twMerge(clsx(inputs));\n}\n```\n\n```ts\nbootstrapApplication(App, {providers: [provideAttributeResolvers({class: cn})]});\n```\n\nAngular reads class values before it calls the resolver, so `twMerge` alone is enough.\n\n### Built-in rules\n\nAn attribute that no provider names uses the built-in rule of its grammar. Three rules are exported,\nso you can name an attribute without writing a function, and one factory creates more:\n\n| Rule | Result |\n| ----------------------- | -------------------------------------------------------------------------------------------------------------------------- |\n| `lastValue` | The last value, which has the highest priority, or `null` when there's none. |\n| `joinTokens` | The tokens without repeated ones, keeping the first, joined with a space. An argument with several tokens counts as those. |\n| `joinDeclarations` | The declarations joined with `; `. |\n| `joinValues(separator)` | The values joined with `separator`, keeping repeated ones, or `null` when there's none. |\n\n```ts\nlastValue('a', 'b'); // 'b'\nlastValue(); // null\njoinTokens('b', 'a b', '', '\\tc\\n', 'a'); // 'b a c'\njoinDeclarations('color: red', 'padding: 4px', 'color: blue'); // 'color: red; padding: 4px; color: blue'\njoinValues(' / ')('a', 'b', 'a'); // 'a / b / a'\n```\n\n`class` has no exported rule. Its built-in rule is the plain merge: it joins the classes in order,\ndrops empty and repeated names, keeping each name's first position, and resolves no conflicts.\n\n### Without a provider\n\nWithout `provideAttributeResolvers()`, every binding uses the built-in rule of its attribute. For\n`class`, the built-in rule merges the collected classes and resolves no utility conflicts. It can\nstill change the DOM. An element with `class=\"a\" [attr.class]=\"'b'\"` has the class `b`, because the\nordinary attribute write replaces the static class. Adding `(class)=\"(cn) => cn()\"` gives it the\nclasses `a b`, because the sources join. For other attributes, the built-in rule can also differ\nfrom Angular's behavior without a binding: in the `MenuItem` example, `lastValue` picks the\ntemplate's value, where Angular without a binding keeps the directive's.\n\nA key whose value is `undefined` provides the built-in rule.\n\n### Where a provider applies\n\nEach binding looks the resolver of its attribute up from its element's injector when Angular\ncreates the element. To resolve a component's template and its own host binding with another\nresolver, provide it in `viewProviders`:\n\n```ts\n@Component({\n selector: 'ui-panel',\n viewProviders: [provideAttributeResolvers({class: panelMerge})],\n host: {class: 'rounded-md', '(class)': 'classes'},\n template: `\n \u003cdiv class=\"p-4\" (class)=\"(cn) => cn()\">\u003c/div>\n \u003cng-content />\n `,\n})\nexport class UiPanel {\n protected readonly classes: ClassCallback = (cn) => cn();\n}\n```\n\n- The `\u003cdiv>` in the template and the host's `(class)` use `panelMerge`.\n- Content that a consumer projects into `\u003cui-panel>`, a consumer's binding on `\u003cui-panel>`, and\n other directives on `\u003cui-panel>` use the resolver provided above `UiPanel`.\n\nSo one element can use two resolvers: the component's host binding uses the component's\n`viewProviders`, and everything else on the element uses the outer one. A component's `providers`\nreach further than its `viewProviders`: they also apply to content projected into it and to every\nbinding on its host element.\n\n### Nested providers\n\nAngular looks each name up separately, through the element's injectors and then its environment\ninjector, such as a lazy route's. A call that doesn't name an attribute leaves that attribute's\nresolver to the injectors above it:\n\n```ts\n@Component({\n selector: 'ui-menu',\n imports: [MenuItem],\n providers: [provideAttributeResolvers({role: joinValues('+')})],\n template: `\u003cli\n menuItem\n role=\"separator\"\n class=\"item\"\n (class)=\"(cn) => cn()\"\n (attr.role)=\"$event.resolve($event.resolver())\"\n >\u003c/li>`,\n})\nexport class UiMenu {}\n```\n\n```ts\nbootstrapApplication(App, {\n providers: [provideAttributeResolvers({class: markRoot, role: joinValues('-')})],\n});\n```\n\n```html\n\u003cli menuitem=\"\" role=\"menuitem+separator\" class=\"item by-root\">\u003c/li>\n```\n\n`class` comes from the root call, and `role` from `UiMenu`'s call. Here `markRoot` appends\n`by-root` to the classes.\n\nWithin one injector, a later call replaces only the names that it names:\n\n```ts\nproviders: [\n provideAttributeResolvers({class: markFirst, role: joinValues('-')}),\n // Replaces `role`. `class` stays `markFirst`.\n provideAttributeResolvers({role: joinValues('+')}),\n];\n```\n\n`provideAttributeResolvers()` reads the map when you call it. Changing the object afterward\nchanges nothing.\n\n### Names\n\n- Names match as written, so `viewBox` and `viewbox` are two attributes with their own resolvers.\n- A namespaced attribute, such as `xlink:title`, can't be resolved.\n- An attribute whose name starts with `on`, in any letter case, can't be resolved. That covers event\n handler attributes, such as `onclick`, and names that aren't events, such as `onboarding`. In dev\n mode, a key for one throws:\n\n ```text\n `provideAttributeResolvers` can't resolve the `onclick` attribute, because Angular never resolves\n an event handler attribute. Remove its key.\n ```\n\nSee also [Attributes that need sanitization](#attributes-that-need-sanitization).\n\n## Grammars\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nThe attribute's name decides how Angular reads its sources, merges them without a provider, and\napplies the result:\n\n| Grammar | Attributes | One entry is | Built-in rule | Applied by |\n| ------------ | --------------------------------------------------------------------------------------------------------- | ------------------------------------- | ------------------ | ------------------------------------------------ |\n| Class list | `class` | a class name | plain merge | adding and removing the classes that changed |\n| Declarations | `style` | a declaration, such as `padding: 4px` | `joinDeclarations` | setting and removing the properties that changed |\n| Token list | `rel`, `part`, `headers`, `aria-describedby`, `aria-controls`, `aria-owns`, `aria-flowto`, `aria-details` | a token | `joinTokens` | setting the attribute, or removing it for `''` |\n| Scalar | every other name, including `id`, `role`, `title`, `aria-labelledby`, and `data-*` | the value of one contributor | `lastValue` | setting the attribute, or removing it for `null` |\n\nThe token list names match as written, in lowercase.\n\n### Class list\n\n- Static classes split on any whitespace, including a no-break space. `[attr.class]` strings split\n on ASCII whitespace only. A `[class]` string splits at every character up to U+0020.\n- Angular applies the difference between the classes it applied last time and the new result.\n\n### Declarations\n\n- When Angular initially collects the sources, each source holds at most one declaration per\n property, written `property: value` or `property: value !important`. A resolver can return\n repeated properties, and the folded sources then keep them. See\n [Several resolvers on one element](#several-resolvers-on-one-element).\n- Property names are written as CSS names them: dash case in lowercase, such as `font-size` for\n `fontSize` and `color` for `COLOR`, a vendor prefix with its leading dash, such as `-webkit-transform` for\n `WebkitTransform`, `float` for `cssFloat`, and a custom property as written. CSS escapes in a\n name are decoded.\n- A declaration marked `!important` beats a later declaration of the same property that isn't,\n and a later removal. A later `!important` declaration replaces an earlier one.\n- Angular applies the resolved declarations in order, property by property. A longhand that comes\n after its shorthand lands after it, and a declaration that overlaps a changed one is written\n again. Styles that something else set, such as `Renderer2.setStyle()` or an animation, stay,\n unless a managed shorthand write or removal affects them. For example, an outside\n `padding-left: 9px` is lost when a managed `padding: 4px` changes to `padding: 8px`.\n- An empty custom property, such as `--x: ;`, is kept. An ordinary property with an empty value is\n dropped.\n\n### Token list\n\n- Each source holds its tokens, split on ASCII whitespace. Repeated tokens stay in the sources.\n- Different tokens from two directives aren't a conflict, so they don't warn.\n\n### Scalar\n\n- Each contributor, the template or one directive, gives at most one value: its static value, or\n its `[attr.x]` binding's value while that isn't `null` or `undefined`.\n- A source has one entry per directive that gives a value.\n- In dev mode, Angular warns when two directives give different values. See\n [Conflicting directive values](#conflicting-directive-values).\n\n\u003c/details>\n\n## Write a binding\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\n### The full form: `(attr.x)`\n\n`(attr.x)` gives its handler a resolve event as `$event`:\n\n```ts\ninterface AttributeResolveEvent {\n readonly sources: AttributeSources;\n resolver(...extras: AttributeValue[]): ResolvedAttribute;\n resolve(value: AttributeValue | ResolvedAttribute | null): void;\n}\n\ntype AttributeValue = string | (readonly string[] & {readonly call?: never});\n```\n\nThe `call` member rejects functions, which an array type alone can't.\n\n- `sources` holds the entries of each source. See [The sources](#the-sources).\n- `resolver(...extras)` merges the sources with extras, using the attribute's resolver.\n- `resolve(value)` sets the attribute to exactly `value`. An array joins with a space. `null`\n removes the attribute, and so does `''` for a token list.\n\n`class` and `style` have their own events, with the same members and their own value types:\n\n| Attribute | `$event` | Extras and `resolve()` take |\n| ------------ | ----------------------- | ------------------------------------------------- |\n| `class` | `ClassResolveEvent` | `ClassBindingValue` |\n| `style` | `StyleResolveEvent` | `StyleBindingValue` |\n| another name | `AttributeResolveEvent` | `AttributeValue`: a string or an array of strings |\n\nThe minimal binding resolves with the attribute's resolver and no extras:\n\n```html\n\u003cli menuItem role=\"separator\" (attr.role)=\"$event.resolve($event.resolver())\">\u003c/li>\n```\n\nA handler can compute the value from component state instead:\n\n```ts\n@Component({\n selector: 'app-card',\n imports: [UiButton],\n template: `\u003cui-button class=\"px-2\" (attr.class)=\"resolveButton($event)\" />`,\n})\nexport class Card {\n readonly plain = input(false);\n\n protected resolveButton(event: ClassResolveEvent) {\n if (this.plain()) {\n // Replaces every class, without the resolver.\n event.resolve(['btn-plain']);\n } else {\n event.resolve(event.resolver('shadow-lg'));\n }\n }\n}\n```\n\n- If the handler doesn't call `resolve()`, the attribute takes the built-in rule of its grammar\n applied to the sources, without the app's resolver. For `class`, the element keeps the classes\n of its sources.\n- The handler's return value is ignored.\n- A chain is allowed: `(attr.role)=\"count(); $event.resolve($event.resolver())\"`.\n- `(attr.x)` never listens to a DOM event named `attr.x`.\n\nEach refresh creates a new event. Call `resolve()` at most once, while the handler runs:\n\n- In dev mode, a second call throws `NG0320`, and so does a call after the handler returns or\n throws. A call from a getter or a proxy that `resolve()` reads counts as a second call. The\n message names the binding's form:\n\n ```text\n NG0320: The `(attr.role)` handler called `resolve()` more than once. Call it at most once.\n ```\n\n ```text\n NG0320: The `(attr.role)` handler called `resolve()` after it returned. Call it while the\n handler runs.\n ```\n\n- In production, a call after the handler returns is ignored. If the handler calls `resolve()` more\n than once, the call that starts last wins.\n\n### Shorthands: `(class)` and `(style)`\n\nThe shorthands take a callback. Angular calls the callback with the element's resolver bound to its\nsources, and applies what the resolver returns:\n\n```html\n\u003cui-button class=\"px-2\" (class)=\"(cn) => cn('shadow-lg', busy() && 'opacity-50')\" />\n\u003cdiv style=\"color: red\" (style)=\"(s) => s({width: size()})\">\u003c/div>\n```\n\n`(class)=\"F\"` means:\n\n```html\n\u003cui-button (attr.class)=\"$event.resolve((F)($event.resolver))\" />\n```\n\n`(style)=\"F\"` means the same with `(attr.style)`. Other attributes have no shorthand.\n\n`F` is one expression whose value is a callback:\n\n```ts\ntype ClassCallback = (cn: BoundClassResolver) => ResolvedAttribute;\ntype BoundClassResolver = (...extras: ClassBindingValue[]) => ResolvedAttribute;\n\ntype StyleCallback = (s: BoundStyleResolver) => ResolvedAttribute;\ntype BoundStyleResolver = (...extras: StyleBindingValue[]) => ResolvedAttribute;\n```\n\nIt takes one of these forms:\n\n```html\n\u003c!-- An arrow function. -->\n\u003cdiv class=\"p-2\" (class)=\"(cn) => cn('m-1')\">\u003c/div>\n\n\u003c!-- A reference to a field. -->\n\u003cdiv class=\"p-2\" (class)=\"withMargin\">\u003c/div>\n\n\u003c!-- An expression that returns a callback. -->\n\u003cdiv class=\"p-2\" (class)=\"margin('m-1')\">\u003c/div>\n```\n\n```ts\n@Component({\n selector: 'app-list',\n template: `...`,\n})\nexport class List {\n protected readonly withMargin: ClassCallback = (cn) => cn('m-1');\n\n protected margin(size: string): ClassCallback {\n return (cn) => cn(size);\n }\n}\n```\n\nA field keeps a callback in one place when it reads component state or when several elements share\nit. Prefer an arrow function field to a method, so the callback keeps `this` however the template\nreads it. See [Type checking](#type-checking).\n\nA shorthand must be a single expression. A chain, such as `(class)=\"count(); classes\"`, is a\ncompile error. Use the full form to run more than one statement.\n\n### Extras\n\nThe arguments that you pass to the resolver are extras. The resolver adds them at the end of the\nsource of the binding that calls it, and merges:\n\n- In a template, extras rank after the template's own entries.\n- In a component's `host`, they rank at the end of the component source, so the consumer's\n template entries still win over them.\n- In another directive's `host`, they rank at the end of the directives source.\n\n`ClassBindingValue` and `StyleBindingValue` are the input types of the resolver. The resolver reads\neach extra by the rules below, which differ from `[class]` and `[style]` in some cases. For example,\nan extra `false` for `class` is valid, where `[class]=\"false\"` throws in dev mode, and a `style`\narray entry such as `'color: red'` is a declaration, where `[style]` reads it as a property name.\nThe resolver reads each extra this way:\n\n- `class`: a string splits on whitespace, an array or a `Set` lists class names, an object map\n keeps the keys whose values are truthy, and `null`, `undefined`, `false`, and `''` add nothing.\n So `cn(active() && 'ring')` works. A name that contains a space, such as the array entry `'a b'`,\n is dropped.\n- `style`: a string holds declarations separated by semicolons, an array lists such strings, an\n object map keeps the properties whose values aren't `null`, `undefined`, or `''`, and a trusted\n style, such as one from `DomSanitizer.bypassSecurityTrustStyle()`, reads as its string.\n- A token list: a string splits into tokens, and an array joins with a space first.\n- A scalar: a string is one value, and an array joins with a space into one value.\n\nWith `provideAttributeResolvers({role: (...values) => values.join('+')})`:\n\n```html\n\u003cli menuItem role=\"separator\" (attr.role)=\"$event.resolve($event.resolver('a', ['b', 'c']))\">\u003c/li>\n```\n\n```html\n\u003cli menuitem=\"\" role=\"menuitem+separator+a+b c\">\u003c/li>\n```\n\nAn extra that repeats an entry of the sources is still its own argument.\n\n### `ResolvedAttribute`\n\nThe resolver of an event returns a `ResolvedAttribute`. It's an opaque value, and only the resolver\nof the current event creates one. It's valid only as the argument of that event's `resolve()`:\n\n- A shorthand callback must return the value that its own resolver gives it. Type checking rejects\n a callback that returns anything else, such as a string. In dev mode, Angular throws `NG0320`:\n\n ```text\n NG0320: The `(class)` callback returned a value that its own resolver didn't create. Return the\n result of the resolver that the callback receives, such as `(cn) => cn('px-4')`.\n ```\n\n- A result of another event, such as another element's, another attribute's, or one kept from an\n earlier refresh, throws `NG0320` in dev mode, in both forms:\n\n ```text\n NG0320: The `(attr.role)` handler passed `resolve()` a result that belongs to another resolve\n event. A result is valid only in the `resolve()` of the event whose `resolver()` created it.\n ```\n\n A shorthand's message reads \"The \\`(class)\\` callback returned a result that belongs to another\n resolve event\".\n\n- A result passed as an extra throws `NG0320` in dev mode:\n\n ```text\n NG0320: The `(attr.role)` handler passed a result to `resolver()`. A result belongs to the\n resolve event that created it and is valid only in that event's `resolve()`. Pass values as\n extras.\n ```\n\n- A function passed to `resolve()` or as an extra throws `NG0320` in dev mode:\n\n ```text\n NG0320: The `(attr.role)` handler passed a function to `resolve()`, which doesn't read\n functions. Pass the value that the function computes.\n ```\n\n- Production skips these checks. A result of the same grammar reads as its value, and a result of\n another grammar reads as no value. A string that a shorthand returns reads as a value. A function\n reads as its source text for a scalar or token list, and as no value for `class` and `style`.\n\nThis makes every shorthand go through the app's resolver, so its result is always the merge of the\nsources and its extras. To set an attribute directly, use the full form.\n\n\u003c/details>\n\n## The sources\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\n`$event.sources` has three slots, ordered from the lowest to the highest priority:\n\n```ts\ntype AttributeSources = readonly [\n component: readonly string[],\n directives: readonly string[],\n template: readonly string[],\n];\n```\n\n`ClassSources` has the same shape. Angular builds the sources with these rules:\n\n1. A missing source is an empty array.\n1. `component` holds the entries of the component on the element and of its host directives,\n which Angular matches before the component.\n1. `directives` holds the entries of all other directives, in the order Angular matched them. That\n order follows the consuming component's `imports`.\n1. `template` holds the element's own entries.\n1. Each contributor's entries come from its static attribute and its bindings of the attribute:\n\n | Attribute | Bindings that are sources, in order within a contributor |\n | ------------ | -------------------------------------------------------- |\n | `class` | `[class]`, then `[class.name]`, then `[attr.class]` |\n | `style` | `[style]`, then `[style.property]`, then `[attr.style]` |\n | another name | `[attr.x]` |\n\n1. A translated static attribute, such as `title=\"Save\" i18n-title`, and a translated attribute\n interpolation, such as `attr.title=\"Hi {{ name() }}\" i18n-attr.title`, count as the template's\n value.\n1. For `class` and `style`, each class or property appears once, under the source and at the\n position of the highest-priority binding that has an opinion about it. A falsy class value, such\n as `false`, `null`, `''`, or `0`, removes the class from every lower-priority source. A `null` or\n `''` style value removes the property. `undefined` defers to a lower priority.\n1. On an element that resolves an attribute, its `[attr.x]` bindings don't write the attribute.\n Only the resolver does.\n\nA property binding that writes the same attribute, such as `[title]` or `title=\"{{ hint }}\"`, isn't\na source. See [Property bindings that bypass a resolver](#property-bindings-that-bypass-a-resolver).\n\nFor example, with a component that has a host directive, and an attribute directive:\n\n```ts\n@Directive({host: {class: 'ring'}})\nexport class Ring {}\n\n@Component({\n selector: 'ui-button',\n hostDirectives: [Ring],\n host: {class: 'cmp-static', '[class]': 'variant()'},\n template: '',\n})\nexport class UiButton {\n readonly variant = signal('cmp-map');\n}\n\n@Directive({selector: '[highlight]', host: {class: 'dir-static', '[class.dir-prop]': 'true'}})\nexport class Highlight {}\n```\n\n```html\n\u003cui-button\n highlight\n class=\"tpl-static\"\n [class]=\"'tpl-map'\"\n [class.tpl-prop]=\"true\"\n (attr.class)=\"capture($event)\"\n/>\n```\n\n```text\n$event.sources: [\n ['ring', 'cmp-static', 'cmp-map'],\n ['dir-static', 'dir-prop'],\n ['tpl-static', 'tpl-map', 'tpl-prop'],\n]\n```\n\nFor `style`, with a component whose host has `[style.width.px]=\"10\"` and\n`[attr.style]=\"'height: 1px'\"`:\n\n```html\n\u003cui-box style=\"color: blue\" (attr.style)=\"capture($event)\" />\n```\n\n```text\n$event.sources: [['width: 10px', 'height: 1px'], [], ['color: blue']]\n```\n\nFor a token list, with these directives:\n\n```ts\n@Directive({selector: '[hint]', host: {'aria-describedby': 'hint shared'}})\nexport class Hint {}\n\n@Directive({selector: '[errors]', host: {'[attr.aria-describedby]': 'ids()'}})\nexport class Errors {\n readonly ids = signal('shared error');\n}\n```\n\n```html\n\u003cinput hint errors (attr.aria-describedby)=\"$event.resolve($event.resolver())\" />\n```\n\n```text\n$event.sources: [[], ['hint', 'shared', 'shared', 'error'], []]\n```\n\n```html\n\u003cinput hint=\"\" errors=\"\" aria-describedby=\"hint shared error\" />\n```\n\nFor a scalar, with a component whose host binds `[attr.id]` to `'cmp'`:\n\n```html\n\u003cui-item id=\"tpl\" (attr.id)=\"capture($event)\" />\n```\n\n```text\n$event.sources: [['cmp'], [], ['tpl']]\n```\n\nWhen the component's binding becomes `null`, the sources become `[[], [], ['tpl']]`. A directive\nwith both a static value and a binding falls back to its static value while the binding is `null`\nor `undefined`.\n\n\u003c/details>\n\n## Attributes that need sanitization\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nA resolved value doesn't go through Angular's sanitizer, so an attribute whose value is a URL, HTML,\nor a script can't be resolved. `style` can, because `[style]` bindings aren't sanitized either.\n\n- In a template, `(attr.x)` is a compile error when `x` needs sanitization on that element:\n\n ```text\n Can't resolve the 'href' attribute of \u003ca>, because its value needs sanitization.\n ```\n\n That covers, for example, `href` on `\u003ca>` in HTML and SVG and on `\u003cmi>` in MathML, `srcdoc` and\n `sandbox` on `\u003ciframe>`, and `src` on `\u003cembed>`. `(attr.src)` on `\u003cimg>` compiles, and its\n sources read a trusted URL as its string.\n\n- In `host`, the element isn't known, so `(attr.x)` is a compile error when `x` needs sanitization\n on any element:\n\n ```text\n Can't resolve the 'href' attribute in a host binding, because its value needs sanitization on\n some elements.\n ```\n\n- An event handler attribute is a compile error everywhere:\n\n ```text\n Can't resolve the event attribute 'onclick' for security reasons.\n ```\n\n- A namespaced attribute is a compile error everywhere:\n\n ```text\n Can't resolve the namespaced attribute 'xlink:title'. Only attributes without a namespace can be\n resolved.\n ```\n\n- Automatic resolution checks each element by its tag and namespace, also in production. It skips\n `href` on `\u003ca>` and resolves it on `\u003cdiv>`. On a host created in code, it reads the element's\n local name and namespace. If the element doesn't tell its namespace, as an element from a\n custom renderer can fail to, only `class` and `style` resolve there.\n\n\u003c/details>\n\n## Resolve a component's host element\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nA component can resolve the attributes of its own host element, so its consumers don't need a\nbinding:\n\n```ts\n@Component({\n selector: 'ui-button',\n host: {class: 'inline-flex h-9 px-4 bg-primary', '(class)': 'classes'},\n template: '\u003cng-content />',\n})\nexport class UiButton {\n readonly disabled = input(false);\n protected readonly classes: ClassCallback = (cn) => cn(this.disabled() && 'bg-muted');\n}\n```\n\nWith `twMerge`, `\u003cui-button class=\"px-2\" />` gets `inline-flex h-9 bg-primary px-2`.\n\nThe full form works in `host` too, for any name that Angular can resolve. Directives and host\ndirectives declare resolvers the same way:\n\n```ts\n@Component({\n selector: 'ui-disclosure',\n host: {'(attr.aria-expanded)': \"$event.resolve(open() ? 'true' : 'false')\"},\n template: '\u003cng-content />',\n})\nexport class UiDisclosure {\n readonly open = signal(false);\n}\n```\n\n### Declaration rules\n\nThe compile errors below use the attribute's name. JIT compilation throws them with the same\nmessages when it compiles the component or directive.\n\n- Declare a resolver in `host`. `@HostListener('class')`, `@HostListener('style')`, and\n `@HostListener('attr.x')` are compile errors:\n\n ```text\n @HostListener('attr.role') can't declare a role resolver. Bind it in the host metadata instead:\n host: {'(attr.role)': 'onRole($event)'}.\n ```\n\n For an attribute that can't be resolved at all, such as `@HostListener('attr.xlink:href')`, the\n error says why instead, as it does for `host`. Angular reads the name the way it reads a `host`\n key, so whitespace around the colon doesn't change the result.\n\n `@HostBinding('class')` and `@HostBinding('attr.role')` still bind values, which become sources.\n\n- A directive has at most one resolver per attribute. `(class)` and `(attr.class)` in one `host`\n object are a compile error, and so are `(style)` and `(attr.style)`:\n\n ```text\n Can't have multiple class resolvers in one host. Use only one '(class)' or '(attr.class)' binding.\n ```\n\n One `host` can resolve several attributes, such as `(class)` and `(attr.role)`.\n\n- A directive inherits its base class's resolvers. If it also declares its own for the same\n attribute, dev mode throws `NG0323` when Angular first creates a template that uses it, because\n the compiler can't always see the base class's host bindings:\n\n ```text\n NG0323: `Sub` has more than one class resolver, through inheritance. A directive can have at most\n one `(class)` or `(attr.class)` binding in its host, including the ones it inherits from its base\n classes.\n ```\n\n- A template element has at most one resolver per attribute. A second one is a compile error, on\n `\u003cng-container>` and `\u003cng-template>` too:\n\n ```text\n Can't have multiple role resolvers on one element. Use only one '(attr.role)' binding.\n ```\n\n- A shorthand must be a single expression, in a template and in `host`:\n\n ```text\n A '(class)' shorthand must be a single expression, a function that receives the resolver. Bind\n '(attr.class)' to run more than one statement.\n ```\n\n\u003c/details>\n\n## Several resolvers on one element\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nAn element can have one resolver per attribute per directive and one from its template. Angular\nruns the resolvers of one attribute from the lowest to the highest priority:\n\n1. The component's host directives, then the component.\n1. The other directives, in match order.\n1. The template.\n\n- The lowest resolver receives the sources as Angular collected them.\n- Angular folds what each resolver resolves back into sources for the next one. An entry that the\n result leaves out is gone for the resolvers above it. The fold keeps every declaration that the\n result holds, so a resolver that returns `color: red; color: blue` gives the next resolver both.\n- The highest resolver's result becomes the attribute's value.\n\nThe fold depends on the grammar:\n\n| Grammar | Where an entry of the result goes |\n| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| Class list | A class keeps the source it had. A new class goes to the resolver's own source: `component` for the component and its host directives, `directives` for other directives, `template` for the template. |\n| Declarations | A declaration keeps the source that had the same declaration. A new one goes to the resolver's own source. |\n| Token list | A token keeps the highest-priority source that had it. A new one goes to the resolver's own source. |\n| Scalar | The value replaces the sources. It goes to the highest-priority source that gave it, or else to the resolver's own source. `null` leaves the sources empty. |\n\nFor example, a directive that resolves `role` itself replaces the template's value for the\nresolvers above it:\n\n```ts\n@Directive({selector: '[tab]', host: {'(attr.role)': `$event.resolve('tab')`}})\nexport class Tab {}\n```\n\n```html\n\u003cli tab role=\"separator\" (attr.role)=\"$event.resolve($event.resolver())\">\u003c/li>\n```\n\n```text\nCollected: [[], [], ['separator']]\nTab: resolve('tab')\nFolded: [[], ['tab'], []]\nTemplate: lastValue('tab')\n```\n\n```html\n\u003cli tab=\"\" role=\"tab\">\u003c/li>\n```\n\nBecause extras rank in the caller's source, a component's extra is a default that the consumer\noverrides. With the `UiButton` above, `provideAttributeResolvers({class: twMerge})`, and this\nconsumer:\n\n```html\n\u003cui-button [disabled]=\"true\" class=\"px-2 bg-red-600\" (class)=\"(cn) => cn('shadow-lg')\" />\n```\n\n```text\nCollected: [['inline-flex', 'h-9', 'px-4', 'bg-primary'], [], ['px-2', 'bg-red-600']]\n\nUiButton, cn('bg-muted')\n twMerge input: 'inline-flex', 'h-9', 'px-4', 'bg-primary', 'bg-muted', 'px-2', 'bg-red-600'\n result: 'inline-flex h-9 px-2 bg-red-600'\n folded: [['inline-flex', 'h-9'], [], ['px-2', 'bg-red-600']]\n\nTemplate, cn('shadow-lg')\n twMerge input: 'inline-flex', 'h-9', 'px-2', 'bg-red-600', 'shadow-lg'\n result: 'inline-flex h-9 px-2 bg-red-600 shadow-lg'\n```\n\nA lower resolver beats a higher source only by removing that source's entry, because the resolvers\nabove it never see the entry again. To drop a consumer's value on purpose, filter `$event.sources`\nin a full-form handler and pass the rest to `resolve()`.\n\n\u003c/details>\n\n## Resolve every element automatically\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\n`withAutoResolution()` makes Angular resolve elements without a binding:\n\n```ts\nbootstrapApplication(App, {\n providers: [provideAttributeResolvers({class: twMerge, role: lastValue}, withAutoResolution())],\n});\n```\n\n```html\n\u003c!-- A component matches: resolved. -->\n\u003cui-button class=\"px-4\" />\n\u003c!-- A directive matches: class and role resolved. -->\n\u003cli menuItem role=\"separator\">\u003c/li>\n\u003c!-- No component or directive: not resolved. -->\n\u003cspan class=\"px-2 px-4\">\u003c/span>\n```\n\n```html\n\u003cli menuitem=\"\" role=\"separator\">\u003c/li>\n```\n\n- Automatic resolution covers `class`, `style`, and the names of every `provideAttributeResolvers()`\n call with `withAutoResolution()` in root providers that turn it on. Calls below the root, and\n calls without the feature, change resolvers but never add names.\n- It resolves every element that a component or directive matches. That includes components\n created in code, such as routed components and components that you create with\n `ViewContainerRef.createComponent()` or `createComponent()`, with their host directives.\n- It skips an attribute that needs sanitization on the element. See\n [Attributes that need sanitization](#attributes-that-need-sanitization).\n- Each attribute takes its resolver from `provideAttributeResolvers()`, or its built-in rule when no\n provider names it. So `provideAttributeResolvers({}, withAutoResolution())` resolves `class` with\n the plain merge and `style` with `joinDeclarations`.\n- Angular calls a resolver with the entries of the sources and no extras, and calls it again only\n when the entries of a source change.\n- An attribute that no source of the element sets isn't touched, so a value that a constructor set\n stays. `class` is the exception: an element without class sources resolves once, with no\n arguments.\n- An attribute with a resolver binding, in the template or in the `host` of a directive on the\n element, is resolved only through its bindings. Automatic resolution doesn't run on that\n attribute, even when the handler doesn't call `resolve()`. The binding's handler runs on every\n refresh, because it can read other state.\n\n### Turn it off for a subtree\n\nDeclare the feature in the root providers, such as those of `bootstrapApplication()` or of\n`TestBed.configureTestingModule()`. Below the root, to turn it off for a component's template,\nprovide `withAutoResolution(false)`. To turn it back on, provide `withAutoResolution()`. A call\nwithout the feature keeps the setting of the providers above it, whichever resolvers it names.\n\n```ts\n@Directive({selector: '[tone]', host: {class: 'px-2'}})\nexport class Tone {}\n\n@Component({\n selector: 'modern-card',\n imports: [Tone],\n // Back on in this template.\n viewProviders: [provideAttributeResolvers({class: twMerge}, withAutoResolution())],\n template: `\u003cdiv tone class=\"px-4\">\u003c/div>`,\n})\nexport class ModernCard {}\n\n@Component({\n selector: 'legacy-table',\n imports: [ModernCard, Tone],\n // Off in this template.\n providers: [provideAttributeResolvers({class: twMerge}, withAutoResolution(false))],\n template: `\u003cmodern-card tone class=\"px-4\" />`,\n})\nexport class LegacyTable {}\n```\n\n```text\n\u003cmodern-card> classes: px-2, px-4\n\u003cdiv> in ModernCard classes: px-4\n```\n\n- The setting applies to the component's template and to the templates nested in it. In an off\n template, elements get the values that Angular gives without a resolver, and resolver bindings\n still resolve.\n- In an on template, automatic resolution uses the resolvers that the template's view sees. A\n resolver binding looks its resolver up from its element's injector instead.\n- An element follows the template that declares it. In the example, `\u003cmodern-card>` isn't resolved,\n because `LegacyTable`'s template declares it, but the `\u003cdiv>` in `ModernCard`'s template is.\n- An embedded view follows the template that declares its `\u003cng-template>`, wherever you insert it.\n- A component created in code follows the injector where you create it. A route's `providers` can\n turn the feature off, or back on with another resolver, for the components it creates.\n\nIf a provider below the root turns the feature on while the root providers don't, dev mode throws\n`NG0322`. That includes root providers that turn it off. Production ignores the feature in that\nprovider.\n\n```text\nNG0322: Automatic resolution is turned on for `ModernCard` by `withAutoResolution()` in providers\nbelow the root, but the root providers don't declare it. Provide\n`provideAttributeResolvers({class: resolver}, withAutoResolution())` in the root providers, such as\nthose of `bootstrapApplication()`.\n```\n\n### Turn it on before the first render\n\nAngular sets up an element for automatic resolution when it first creates the element's template,\nand it caches that setup with the component. It sets up the names that are listed by then. The\nfeature's hooks turn on when you call `withAutoResolution()`. That call enables the hooks, and it\ndoesn't list the custom names. A root's names are listed when Angular first evaluates the root's\nautomatic-resolution setting, which happens during a component's setup after the check that the\neffective setting is on. Creating the first component through an injector where the feature is off\ntherefore leaves the root's custom names unlisted. So:\n\n- A template that Angular created before the first `withAutoResolution()` call never gets\n automatic resolution in that JavaScript process, in any app.\n- A template that Angular created before a root listed a name never resolves that name, in any\n app. To list a custom name, create a component through an injector where the feature is on\n before the first creation of any template that needs the name.\n\nAn app whose root providers call `withAutoResolution()` before its first render isn't affected. Two\ncases are:\n\n- Several apps in one process, where an app without the feature, or with fewer names, renders a\n shared component first.\n- Tests, where an earlier test renders a component before a later test provides the feature or a\n name. Call `withAutoResolution()` in your test setup file, before any test renders, to enable the\n hooks. That call doesn't list custom names. To list them, provide them with the feature on in the\n root providers of the test that renders first. Calling `withAutoResolution()` in setup alone\n doesn't turn automatic resolution on in a test whose root providers don't provide it.\n\nAngular gives no signal, in dev mode or in production: the affected elements keep their values\nunresolved.\n\n\u003c/details>\n\n## When handlers run\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nAngular calls an element's handlers on every refresh of the view that declares the element, after\nthe view's host bindings and before its child components. It then applies the difference between\nthe value it applied last time and the new result:\n\n- `class`: it adds and removes classes. Classes that something else added, for example\n `Renderer2.addClass()` or an animation, stay.\n- `style`: it sets and removes properties in the resolved order. Properties that something else\n set, for example `Renderer2.setStyle()` or an animation, stay, unless a managed shorthand write or\n removal affects them. See [Declarations](#declarations).\n- Another attribute: it sets or removes the attribute only when the resolved value changes.\n\nAngular calls the handler while it renders the view, like a template expression:\n\n- Signals that the handler reads are tracked, so a change to them schedules a refresh.\n- Writing a signal in the handler throws `NG0600`.\n- Writing a plain field that the element's own bindings read leaves the element out of date. An\n `OnPush` view, the default, doesn't report it. Dev mode reports it as `NG0100` in an `Eager` view,\n and `provideCheckNoChangesConfig({exhaustive: true})` reports it in any view.\n\nIn an embedded view, such as an `@if` or `@for` block, each view resolves its own elements, and the\nhandler reads that view's context, such as the `@for` item.\n\nWrite the handler as a function of its sources and the state it reads.\n\n\u003c/details>\n\n## Conflicting directive values\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nIn dev mode, when two directives on one element give different values for a resolved scalar,\nAngular logs `NG0324` with `console.warn`, once per element and attribute. The template's value\ndoesn't count, and the warning appears with any resolver, including `joinValues()`:\n\n```text\nNG0324: Directives `TestId` and `BoundTestId` set different values for the `data-testid`\nattribute of an element: `static-id` and `bound-id`. Reconcile the values that the directives\ncontribute, for example by setting the attribute in only one of them.\n```\n\nThe resolver still runs. With `lastValue`, the later directive's value wins. Token lists never\nwarn.\n\n\u003c/details>\n\n## Property bindings that bypass a resolver\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nA property binding isn't a source, but it still writes the attribute, and its later writes can stay\nin the DOM while the resolved value doesn't change. The extended diagnostic\n`propertyBindingBypassesResolver` (`NG8122`), a warning by default, reports one next to a resolver\nof the same attribute:\n\n```html\n\u003cbutton [title]=\"hint\" (attr.title)=\"$event.resolve($event.resolver('Save'))\">\u003c/button>\n```\n\n```text\nThe `title` property binding writes the `title` attribute, which the element's `(attr.title)`\nbinding resolves. The resolver doesn't receive the binding's value, and the binding's later writes\ncan stay in the DOM while the resolved value doesn't change. Bind `[attr.title]` instead to make\nthe value a source of the resolver.\n```\n\nBind `[attr.title]` instead. For `class` and `style`, `[class]`, `[class.x]`, `[style]`, and\n`[style.x]` are sources too.\n\n- It checks properties that map to an attribute of another name, such as `[className]` for\n `class` and `[tabIndex]` for `tabindex`, interpolations such as `title=\"{{ hint }}\"`, translated\n interpolations, and ARIA bindings such as `[aria-label]`.\n- It checks the host bindings and host resolvers of the element's directives, including the ones\n that a directive inherits from local base classes, when `typeCheckHostBindings` is on, the\n default. It reports a host binding on the element, once per template.\n- A binding that a directive input claims isn't reported, because it never writes the DOM.\n- It runs only with `strictTemplates`, like every extended diagnostic.\n\n\u003c/details>\n\n## Directive outputs that a resolver binding shadows\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nA resolver binding always resolves its attribute, in a template and in `host`, even next to a\ndirective output of the same name: `(class)` next to an output named `class`, `(style)` next to\n`style`, and `(attr.role)` next to `attr.role`. That includes a host directive's output that the\ncomponent exposes under that name. The binding never listens to the output, and type checking gives\n`$event` the resolve event's type, not the output's type.\n\nThe extended diagnostic `outputShadowedByAttributeResolver` (`NG8120`), a warning by default,\nreports such a binding in a template. It runs only with `strictTemplates`:\n\n```text\nThe `(class)` binding resolves the element's classes, so it doesn't listen to the `class` output of\n`Emitter`. Rename the output to listen to it.\n```\n\nFor another attribute, the message reads \"resolves the element's \\`role\\` attribute\". Rename the\noutput to listen to it.\n\n\u003c/details>\n\n## `\u003cng-container>` and `\u003cng-template>`\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nThese elements aren't rendered, so they have no attributes to resolve. A resolver binding on them\ndoes nothing, and it doesn't listen to a directive output either.\n\n- At compile time, the TypeScript compiler reports `NG8121`, an error, for a binding on\n `\u003cng-container>`, also inside `\u003csvg>` or `\u003cmath>`:\n\n ```text\n The '(attr.role)' binding can't resolve the 'role' attribute on '\u003cng-container>' or\n '\u003cng-template>', because neither is rendered as an element. Bind it on an element instead.\n ```\n\n For `class`, the message reads \"can't resolve classes\". Type checking doesn't see a binding on\n `\u003cng-template>` itself.\n\n- At runtime, dev mode logs `NG0321` with `console.error` when Angular creates the binding. This\n also covers a binding on `\u003cng-template>` and a directive's host binding on these elements, which\n type checking can't see. The handler never runs.\n\n ```text\n NG0321: The `(class)` binding can't resolve classes on `\u003cng-container>` or `\u003cng-template>`,\n because neither is rendered as an element. Bind it on an element instead.\n ```\n\n ```text\n NG0321: The `(attr.role)` host binding of `Recorder` can't resolve the `role` attribute on\n `\u003cng-container>` or `\u003cng-template>`, because neither is rendered as an element. Apply `Recorder`\n to an element instead.\n ```\n\n### Other names\n\n- An event with a target, such as `(window:class)` or `(document:class)`, is an ordinary listener,\n in a template, in `host`, and in `@HostListener`.\n- `[(class)]` is a two-way binding to an input named `class`, not a resolver.\n\n\u003c/details>\n\n## Type checking\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nWith `strictOutputEventTypes`, which `strictTemplates` turns on by default:\n\n- `$event` is a `ClassResolveEvent` for `class`, a `StyleResolveEvent` for `style`, and an\n `AttributeResolveEvent` for any other name, in both forms, in a template and in `host`.\n- Angular checks a shorthand `(class)=\"F\"` as the call that runs,\n `$event.resolve((F)($event.resolver))`, with two more checks: `F` must satisfy `ClassCallback`,\n and the call's result must satisfy `ResolvedAttribute`. `(style)` is checked the same way, with a\n callback that receives `StyleResolveEvent['resolver']`.\n- Extras and `resolve()` arguments must fit the attribute's value type. For example,\n `$event.resolve(false)` fits `class` but not `role`, a `Set` fits `class` but not `role`, and\n `style` rejects numbers, booleans, and functions.\n\nThe parameter of an arrow function gets the resolver's type, whatever you name it. The checks catch\nthese mistakes:\n\n| Template | Error |\n| --------------------------------------------------------- | --------------------------------------------------------- |\n| `(class)=\"(cn) => 'x'\"` | `TS2322` and `TS1360`: a string isn't `ResolvedAttribute` |\n| `(class)=\"(cn) => cn(42)\"` | `TS2345`: `42` isn't a `ClassBindingValue` |\n| `(class)=\"classes()\"`, where `classes()` returns a string | `TS2349` and `TS1360`: a string isn't callable |\n| `(class)=\"() => saved\"` | `TS2554`: the callback takes no parameter |\n| `(class)=\"choice?.classes\"`, with a nullable `choice` | `TS1360`: `undefined` isn't a `ClassCallback` |\n| `(style)=\"(s) => 'x'\"` | `TS2322` and `TS1360`: a string isn't `ResolvedAttribute` |\n| `(attr.role)=\"$event.resolve(false)\"` | `TS2345`: `false` isn't an `AttributeValue` |\n| `(attr.role)=\"count($event)\"`, with `count(n: number)` | `TS2345`: `AttributeResolveEvent` isn't a `number` |\n\nFor an overloaded method, Angular checks the overload that the call selects, and its result.\n\nBecause Angular checks the call that runs, it also checks `this`:\n\n- `(class)=\"classes\"` calls the method on the component, so the method keeps `this`.\n- `(class)=\"active ? first : classes\"` calls the method without `this`. If the method declares a\n `this` parameter, such as `classes(this: Toolbar, cn: BoundClassResolver)`, type checking reports\n `TS2684`. If it doesn't, type checking accepts it, and the method runs without `this`.\n\nA wrong callback can report up to three errors, all on the callback:\n\n```ts\nonClick(event: MouseEvent): void {}\n```\n\n```html\n\u003c!-- TS1360 for ClassCallback, TS2345 for the argument, and TS1360 for the void result. -->\n\u003cdiv (class)=\"onClick\">\u003c/div>\n```\n\nWith `strictOutputEventTypes: false`, `$event` is `any`. `strictTemplates` supplies the default of\nthat option. An explicit `strictOutputEventTypes: true` keeps the resolver's event checks when\n`strictTemplates` is `false`, in the parts of a template that Angular checks; it doesn't restore the\nchecks of `\u003cng-template>` and control flow bodies that `strictTemplates: false` turns off. Type checking skips the callback, result, and value checks, but it still checks the\ncall itself and the ordinary expressions, so it still reports a lost `this` (`TS2684`).\n\nThe extended diagnostic `uninvokedFunctionInEventBinding` (`NG8111`), which runs only with\n`strictTemplates`, doesn't report a `(class)` or `(style)` shorthand, because the shorthand passes\nits function on purpose. Calling the function by mistake, as in `(class)=\"classes()\"`, fails type\nchecking instead. `NG8111` reports `(attr.class)=\"resolve\"` like any other event binding. It reports\nno resolver on `\u003cng-container>` or `\u003cng-template>`.\n\n\u003c/details>\n\n## Server rendering and hydration\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nOn the server, resolvers run as in the browser, and the HTML carries the resolved values. Resolved\nstyles serialize in the order that they resolve to. When hydration claims an element that a\nbinding or automatic resolution resolves, the first resolution in the browser reconciles the\nserver's value:\n\n- `class`:\n - If the element has static classes, Angular rewrites its `class` attribute to them when it\n claims the element, and the first resolution starts from them. Classes that only the server\n resolved are removed.\n - If the element has no static classes, the first resolution starts from the classes the\n element has and removes the ones that no longer resolve. That also removes classes that a\n directive's constructor added.\n- `style`:\n - If the element has no static styles, the first resolution removes every property that its\n sources name and the result doesn't set. Other properties, such as one that a constructor set,\n stay.\n - If the element has static styles, Angular rewrites its `style` attribute to them when it claims\n the element. Styles that only the server resolved or that only the server's constructor set\n are lost.\n- Another attribute: the first resolution compares the result with the server's value, and sets\n or removes the attribute when they differ.\n\nThe same applies to the host element of a root component. A host element that the server didn't\nrender, such as one that you pass to `createComponent()`, keeps the classes it had, next to the\nresolved ones. In a subtree where automatic resolution is off, elements hydrate with the values\nthat Angular gives without a resolver.\n\n\u003c/details>\n\n## Libraries compiled in partial mode\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\nA partial declaration declares `minVersion: \"22.3.0\"` when:\n\n- Its template has a resolver binding, `(class)`, `(style)`, or `(attr.x)`, on any element,\n including `\u003cng-container>` and `\u003cng-template>`.\n- Its host has a `(class)`, `(style)`, or `(attr.x)` binding. A host listener with a target, such as\n `(window:class)`, doesn't count.\n\nAn older linker, which would compile the binding as a plain listener, rejects the declaration.\n\nThe linker and JIT compilation read every host listener named `class`, `style`, or `attr.x` as a\nresolver, also in a declaration from an older library. They check its name, so a host\n`(attr.href)` or `(attr.xlink:title)` listener from an older library throws with the messages in\n[Attributes that need sanitization](#attributes-that-need-sanitization).\n\n\u003c/details>\n\n## Error conditions\n\nSee Flarette/angular#9.\n\n## Limitations\n\n\u003cdetails>\n\u003csummary>Show the section\u003c/summary>\n\n### Sources and values\n\n- Values set outside bindings, for example by `Renderer2.addClass()`, `Renderer2.setStyle()`,\n `NgClass`, or animations, aren't sources, so a resolver can't resolve conflicts with them. Prefer\n `[class]` over `[ngClass]` on these elements.\n- Angular stores a `[class]` value and a `[style]` map sorted by name, so conflicts inside one such\n value resolve alphabetically. Extras keep their order, so `(class)=\"(cn) => cn(value)\"` resolves\n `value` in the order you write.\n- A directive with an input named or aliased `class` or `style`, as spartan-ng uses for `class`,\n receives the template's `[class]` or `[style]` binding, so that binding isn't a source. The\n template's static `class` or `style` still is.\n- For `class`, static classes, extras, `resolve()` values, and the resolver's returned string split\n on any whitespace, including a no-break space. `[attr.class]` strings split on ASCII whitespace\n only, and a `[class]` string splits at every character up to U+0020.\n- A resolver writes only its own attribute. It can't split one value into several attributes.\n\n### Styles\n\n- The style resolver models a subset of CSS: a table of shorthands and their longhands, and a small\n tokenizer for declarations. It doesn't implement full CSS Syntax. The table doesn't link logical\n and physical properties, vendor-prefixed aliases, or `all`.\n- How the importance of a shorthand and of its longhands interact isn't modeled. Only declarations\n of one property follow the `!important` rule. A lower-priority `!important` declaration still\n wins after a join, as in CSS.\n- Hydration of `style` reconciles by ownership. A server-only property from a `[style]` map key that\n the client's map doesn't have stays on the element. On an element with static styles, styles that\n only the server resolved or set are lost.\n- When Domino writes the `style` attribute on the server, it doesn't escape property names. So the\n server's HTML can differ from the browser's for a custom property whose decoded name contains a\n character such as `;`.\n- With Domino on the server, a static host style whose property name uses a CSS escape, such as\n `\\63 olor: red !important`, reaches the resolver as `color`, but the element can render the\n template's value for that property.\n\n### Automatic resolution\n\n- Only the root providers can turn automatic resolution on and list its names.\n- A template that Angular first created before a name enrolls doesn't resolve that name. See\n [Turn it on before the first render](#turn-it-on-before-the-first-render).\n- The names that automatic resolution covers, and the injection token of each name, live in\n module-level registries for the lifetime of the JavaScript process. They never shrink.\n- Automatic resolution reserves five `LView` slots for each automatically enrolled name that is\n eligible on an element that a component or directive matches, also in instances where it's off.\n It reserves none for a name that is excluded for security on that element or that the element\n already resolves through a binding.\n\n### Resolvers and results\n\n- An app's resolver receives one argument per value. A list longer than the JavaScript engine's\n argument limit, such as 200,000 classes or tokens, throws there. The built-in rules and resolvers\n from `joinValues()` read the list as an array and don't throw.\n- In production, a function passed to `resolve()` or as an extra of a scalar or token list becomes\n its source text. For `class` and `style`, it reads as no value. Dev mode throws `NG0320`.\n- Strict templates accept a result of another event, because every result has the one type\n `ResolvedAttribute`. Only dev mode reports it.\n- In dev mode, a `resolve()` call that throws `NG0320` for its argument still counts as the call,\n so a handler that catches the error and calls `resolve()` again gets the \"more than once\" error.\n- The `checkNoChanges` pass doesn't run the handlers, so it doesn't verify that they're stable.\n\n### Compiler and type checking\n\n- `NG8122` matches a binding to a resolved attribute whose name is lowercase. So it still reports a\n property that doesn't write its attribute, such as `[value]` on `\u003cinput>`, `[checked]`,\n `[selected]`, or `[muted]`, next to an `(attr.x)` of the same lowercase name.\n- `NG8122` follows a base class through `extends` only when the class is declared locally or\n imported. A base class reached through a value alias, such as `const Alias = Base`, stops the\n walk. It also doesn't check resolvers that automatic resolution adds, directives inside an\n `ngNonBindable` element, host bindings of directives and base classes from libraries, or a\n `@HostBinding` on a getter.\n- A shorthand that reads its callback through a safe read, such as `(class)=\"choice?.classes\"`, can\n call it without `this`, depending on how the compiler emits optional chaining. Type checking\n doesn't report it. Use an arrow function field.\n- Type checking doesn't report a binding on `\u003cng-template>`. Only the runtime `NG0321` does.\n- The `ngp` compiler backend doesn't run most of these checks. It skips these:\n - The host resolver rules under `NG5001`, including a host `(attr.href)`.\n - The type checks of resolver bindings.\n - `NG8120`, `NG8121`, and `NG8122`.\n - `minVersion: \"22.3.0\"` for a binding on `\u003cng-container>`.\n\n For `NG8111`, it doesn't report the full form, and it reports a `(class)` or `(style)`\n shorthand as never invoked.\n\n### Bundle size and hydration edge cases\n\n- A single resolver binding, such as one `(attr.role)`, pulls in the whole resolver runtime, the\n style code included: about +7.1 kB gzip over an app without one, as the linked benchmark measures. See\n [the cost measurements](https://github.com/Flarette/angular/issues/8).\n- If a directive's constructor calls `ViewContainerRef.createEmbeddedView()`, its element can keep\n values that only the server resolved after hydration.\n- When an element has two translated attribute interpolations and the translation of the first\n drops its placeholders or is empty, the second can read the first one's expression. This also\n happens without a resolver.\n\n\u003c/details>\n\n## Tests\n\nSee Flarette/angular#9.\n","author":{"url":"https://github.com/Flarette","@type":"Person","name":"Flarette"},"datePublished":"2026-03-09T09:08:50Z","url":"https://github.com/angular/angular/issues/67519"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:4d3c5377-2ee7-a9db-c05c-42390e8a1be8 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | BF68:25598F:DBE12E:1238D5F:6B00FE10 |
| html-safe-nonce | cf3447541bc1af22eff858c8b3ee3850a9d79b80fb8fbe975c764a65b5bc189e |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCRjY4OjI1NTk4RjpEQkUxMkU6MTIzOEQ1Rjo2QjAwRkUxMCIsInZpc2l0b3JfaWQiOiIyNDk3MjkzMDUwODMzODYyMTYwIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 3450b5333dd77c11164b7fc10eb311128edf13c51ace356866f22435283a58a2 |
| hovercard-subject-tag | issue:4044330750 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/angular/angular/67519/issue_layout |
| twitter:image | https://opengraph.githubassets.com/d25c64a82dc9209032bf4e0baf7556139ac7d692ebbc0a0a24b5bc183edfb927/angular/angular/issues/67519 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/d25c64a82dc9209032bf4e0baf7556139ac7d692ebbc0a0a24b5bc183edfb927/angular/angular/issues/67519 |
| og:image:alt | Attribute resolvers NoteImplemented in #71966. This description is the feature reference. Why it works this way: Flarette#10, design decisions and the alternatives that lost. Numbers: Flarette#7, t... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | Flarette |
| hostname | github.com |
| expected-hostname | github.com |
| None | e208d86428ec00a57ade75058166297440e8128a01e5287c31a53dc042bbf187 |
| turbo-cache-control | no-preview |
| go-import | github.com/angular/angular git https://github.com/angular/angular.git |
| octolytics-dimension-user_id | 139426 |
| octolytics-dimension-user_login | angular |
| octolytics-dimension-repository_id | 24195339 |
| octolytics-dimension-repository_nwo | angular/angular |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 24195339 |
| octolytics-dimension-repository_network_root_nwo | angular/angular |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 7dafd017fb7809a839c443dba08622af38e63c09 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width