Repository navigation
Description
Which @angular/* package(s) are relevant/related to the feature request?
core, compiler, compiler-cli
Description
Angular applies the union of an element's classes from the component's host, its other directives, and the template. With utility CSS such as Tailwind, conflicting classes both stay, and the stylesheet picks the winner:
@Component({
selector: 'ui-button',
host: {class: 'px-4 py-2'},
template: '<ng-content />',
})
export class UiButton {}<ui-button class="px-2">Save</ui-button>
<!-- Today: class="px-4 py-2 px-2". px-2 may or may not win. -->
<!-- Wanted: class="py-2 px-2". -->Libraries work around it with an input aliased to class and a computed host [class], as spartan-ng does. That can't see [class.x] bindings or other directives' classes, and each library reimplements it.
Proposed solution
An app provides a resolver, and a (class) binding resolves an element's classes with it. A prototype is implemented and tested: Flarette#5. Reference: https://github.com/Flarette/angular/blob/feat/class-resolver/docs/class-resolver.md
Provide a resolver
bootstrapApplication(App, {providers: [provideClassResolver(twMerge)]});
// Angular calls it with one string per source, lowest priority first:
twMerge('px-4 py-2' /* component */, '' /* directives */, 'px-2' /* template */); // 'py-2 px-2'Any (...classes: string[]) => string fits. Without a provider, classes merge as they do today. A library can scope its own resolver with viewProviders.
Resolve a component's host
@Component({
selector: 'ui-button',
host: {class: 'px-4 py-2 bg-primary', '(class)': 'classes'},
template: '<ng-content />',
})
export class UiButton {
readonly disabled = input(false);
protected readonly classes: ClassCallback = (twMerge) => twMerge(this.disabled() && 'bg-muted');
}<ui-button class="px-2" />
<!-- class="py-2 bg-primary px-2" -->
<ui-button class="px-2 bg-danger" [disabled]="true" />
<!-- class="py-2 px-2 bg-danger": the template still wins over the component's extra bg-muted -->Resolve in a template
<ui-button class="px-2" (class)="(twMerge) => twMerge('shadow-lg', busy() && 'opacity-50')" />(class)="F" is shorthand for (attr.class)="$event.resolve((F)($event.resolver))". The full form gives a handler the classes of each source:
@Component({
selector: 'app-toolbar',
imports: [UiButton],
template: `<ui-button class="px-2" (attr.class)="resolveButton($event)" />`,
})
export class Toolbar {
readonly busy = signal(false);
readonly compact = signal(false);
protected resolveButton(event: ClassResolveEvent) {
// event.sources, after UiButton's own host resolver ran:
// [['py-2', 'bg-primary'], [], ['px-2']]
if (this.compact()) {
event.resolve('px-1 py-1'); // exact classes, no resolver
} else if (this.busy()) {
event.resolve(event.resolver('opacity-50')); // twMerge with an extra class
}
// No resolve() call: the element keeps the classes as collected.
}
}The shorthand must return what its resolver returns. Both of these are compile errors:
<div (class)="(twMerge) => 'px-2'"></div>
<div (class)="onClick"></div>Resolve every element
bootstrapApplication(App, {providers: [provideClassResolver(twMerge, withAutoResolution())]});
@Component({
// Off for this component's template.
viewProviders: [provideClassResolver(twMerge)],
})
export class LegacyWidget {}Every element that a component or directive matches resolves without a binding.
Several resolvers on one element
Priority: template > directives > component. Every resolver runs, lowest priority first, and each gets the previous result as its sources.
@Component({
selector: 'ui-button',
host: {class: 'px-4 bg-primary', '(class)': 'resolve'},
template: '<ng-content />',
})
export class UiButton {
protected readonly resolve: ClassCallback = (twMerge) => twMerge('rounded');
}
@Directive({
selector: '[tone]',
host: {class: 'bg-gray-100', '(class)': 'resolve'},
})
export class Tone {
protected readonly resolve: ClassCallback = (twMerge) => twMerge('text-gray-900');
}<ui-button tone class="px-2 bg-white" (class)="(twMerge) => twMerge('shadow')" />sources component 'px-4 bg-primary' directives 'bg-gray-100' template 'px-2 bg-white'
1. UiButton component 'rounded' directives '' template 'px-2 bg-white'
2. Tone component 'rounded' directives 'text-gray-900' template 'px-2 bg-white'
3. template class="rounded text-gray-900 px-2 bg-white shadow"
Each resolver's extra classes join its own source, so a component's extras are defaults that directives and the template override.
Cost
About 2 µs or less per resolved element in dev mode, not counting the resolver. Apps that don't use it don't bundle it.
Breaking changes
@Directive({selector: '[dir]'})
export class Dir {
// `<div dir (class)="...">` no longer listens to this output. NG8120 warns.
readonly class = output<string>();
}@HostListener('class') onClass() {} // Now a compile error.Outputs named class are rare. Until #71661, such an output also dropped the element's [class] binding, so apps are unlikely to depend on one.
Alternatives considered
Today's alternative is the userland workaround above. The open design choices, with why the prototype chose what it did:
-
All attributes, not only
class.aria-describedbyand other token lists have the same problem:provideAttributeResolvers({class: twMerge, 'aria-describedby': joinIds});
The prototype resolves only
class, because each attribute needs its own merge rule. Other(attr.*)names stay ordinary event bindings, so the namespace is still free for this. -
Styles. A
(style)counterpart that resolves conflicting style declarations. Not designed yet. -
The shorthand's shape. Today the callback gets only the bound resolver. It could also get the sources:
<!-- Today --> <div (class)="(twMerge) => twMerge('px-2')"></div> <!-- With the sources as a second argument --> <div (class)="(twMerge, sources) => twMerge(...sources[0], 'px-2')"></div> <!-- The first prototype: the callback got the sources and returned the classes, which a component method merged --> <div (class)="(sources) => merge(sources, 'px-2')"></div>
Why the prototype chose today's shape:
- The callback returns what the resolver returns. An earlier version used a handler's return value as the classes. No other Angular event does that, the value wasn't type-checked, and a later statement in a handler could replace the classes silently. The result is now an opaque type that only the resolver creates, so the compiler rejects
(twMerge) => 'px-2', and a cast fails in dev mode. - The sources stay in the full form. A handler that needs them uses
(attr.class)and$event.sources. The shorthand stays one call for the common case. - Extras join the caller's source. Appending them after every source let a component's extras beat the consumer's classes.
- The resolver takes and returns strings:
(...classes: string[]) => string. A string is what a DOM attribute takes natively, for any attribute, so the same contract can serve a resolver for any attribute.classadds one step: Angular first reads extras andresolve()values the way a[class]binding does, so arrays, Sets, and object maps work, andfalseadds nothing.twMergeand a shadcncnfit unchanged. A contract that takes[class]values failstwMerge's types, and declaration merging for the extras' type breaks when two libraries augment it differently.
- The callback returns what the resolver returns. An earlier version used a handler's return value as the classes. No other Angular event does that, the value wasn't type-checked, and a later statement in a handler could replace the classes silently. The result is now an opaque type that only the resolver creates, so the compiler rejects
-
Several resolvers. Every resolver runs, and each gets the previous result back in its sources. Letting one resolver replace the others depended on
importsorder and dropped a library's logic silently. Letting a lower resolver delegate upward let its appended classes beat the consumer's. -
Naming.
(class)and(attr.class)collide with outputs namedclass. A name such as(class.resolve)avoids the breaking change, but it loses the short form, and(class.x)reads like a modifier, as in(keydown.enter). -
Automatic resolution's reach. It could resolve every element. The prototype chose not to: every element would pay the extra cost, and an element that no component or directive matches has only the template's classes, so it has no conflict to resolve. A template that needs a merge there can import
twMergeand bind[class]to its result. Resolving every element would trade explicitness and performance for consistency and less boilerplate.
RFC
The class resolution is a special case of the #67519, Angular has no API for resolving host conflicts and relies on defaults (classes join, Id's override). Other frameworks avoid it by not having the selectors, in angular it is a friction point. The full feature could resolve any attribute, with shorthands such as (class) for the common cases or cases with special defaults ex: (class) accepting same types as [class]. Before proceeding with the implementation i want to hear the opinion of the maintainers and users if this API fits the angular vision
Activity
[-]Resolve conflicting classes from a component, its directives, and its template[/-]