Skip to content

Warn on Duplicate Directive Usage in Templates #63797

@SkyZeroZx

Description

@SkyZeroZx

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

@angular/compiler or @angular/compiler-cli

Description

Currently, Angular allows the same directive to be applied multiple times on a single element. For example:

<section myDummyDirective myDummyDirective>
  <h2>Section Title</h2>
  <p>Awesome content goes here...</p>
</section>

This code compiles and runs, but at runtime the first directive instance is destroyed, which can lead to unexpected behavior, subtle bugs, and potential conflicts.

Proposed solution

Introduce a compiler warning that detects duplicate directive usage on the same element.

  • Detect when the same directive appears more than once on a single element.
  • Emit a diagnostic warning with a clear message.
  • Continue allowing compilation, but alert developers of potential issues.

Message

 Duplicate directive 'myDummyDirective' found on the same element. The first instance will be destroyed at runtime. Consider removing duplicates to avoid conflicts.

I could work on the PR that proposes to generalize both the ARIA, Style, Class, and Attribute elements to have it at the compile level or can it be considered only at the compile level?
#63749

Alternatives considered

ESLint works well for this case, but if a user relies only on the extension/lib, it may fail silently. And it might not detect more complex cases.

https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin-template/docs/rules/no-duplicate-attributes.md?utm_source=chatgpt.com

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions