Skip to content

Extended ngClass array syntax (allow strings and literals) #47279

@moniuch

Description

@moniuch

Which @angular/* package(s) are relevant/related to the feature request?

core

Description

Currently, the [ngClass] syntax is limited to only strings or only literals. When both are provided (using two separate [ngClass] inputs - one with strings, the other with literal) - only one is rendered. In order to mix the incoming values, dev has to use some sort of ts helper that produces the literal.

Proposed solution

I would propose that Angular adopt a new array-based syntax for [ngClass]. The NgClassSupportedTypes union would be extended by:

Array<string | Record<string, boolean | undefined | null>>

In practice, dev would be able to provide an array of strings mixed with literals, depending on how a given css class is provided. Usage example:

[ngClass]="['fixed-class', input1, input2, {'flagged1': bool1, 'flagged2': bool2}, input3$ | async]"

I think this syntax would reduce the code that today has to be handled by the TypeScript code (via getters, methods, HostBindings and whatnot), or get scattered over html and ts, thus making the code verbose and hardly manageable.

Alternatives considered

As mentioned, yes, certainly, workarounds exist, but they essentially produce overcomplicated and hardly maintainable code. The proposed syntax would consolidate css classes into one expression and move it close to the html element.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: commonIssues related to APIs in the @angular/common packagearea: coreIssues related to the framework runtimecore: styling bindingsfeatureIssue that requests a new featurefeature: insufficient votesLabel to add when the not a sufficient number of votes or comments from unique authors

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions