1851 Commits

Author SHA1 Message Date
Matthew Beck 7b0bc4e395 test(compiler-cli): add compliance case for @HostListener on a property
`@HostListener` is not limited to methods — it is equally valid on a property
holding a function, which is the idiomatic way to keep `this` bound:

    @HostListener('window:beforeunload', ['$event'])
    private onUnload = (event: BeforeUnloadEvent) => {...};

Every existing host-listener compliance case declares the handler as a method,
so the property form was uncovered. This adds a case exercising both a public
and a private function-valued property, one of them with a global (`window:`)
event target, and locks in the emitted chained `ɵɵlistener` calls plus
`ɵɵresolveWindow`.

Verified against all four compliance modes (full, partial/linked,
declaration-only); GOLDEN_PARTIAL.js regenerated via the golden update rule.

(cherry picked from commit d44b3224d9)
2026-07-29 08:52:57 -07:00
SkyZeroZx 2df018fe25 fix(core): sanitize host bindings on concrete hosts (#69558)
Host binding sanitization previously used the declaring directive or component selector to choose a compile-time security context. The same host binding can execute on a different concrete element through hostDirectives, inherited host bindings, dynamic directives, or createComponent hostElement usage.

Compute host binding security contexts against possible concrete hosts and defer URL versus ResourceURL selection to runtime when necessary. Resolve dynamic root host TNodes to their native tag before sanitizer and security-sensitive attribute checks.

Fixes angular#69550

PR Close #69558
2026-07-29 08:36:33 -07:00
Matthew Beck ffc2fb4838 test(compiler-cli): format compliance TEST_CASES.json with prettier
Reformats the TEST_CASES.json files touched by the following change so they
satisfy the repo's prettier check (short inputFiles/files arrays collapsed to a
single line). Pure formatting; the parsed JSON is unchanged. Split into its own
commit so the coverage change that follows is easy to review.

(cherry picked from commit 5245ca5ba7)
2026-07-24 13:55:37 -07:00
Matthew Beck 7eec520725 test(compiler-cli): cover DOM-only vs full instruction set across compilation modes
Adds a compliance case pinning the instruction-set selection for a
directive-free standalone component:

  - full compile: the compiler can prove the template has no directive
    dependencies, so it takes the DOM-only fast path
    (`ɵɵdomElementStart`/`ɵɵdomElementEnd`).
  - local compile: the compiler cannot inspect dependencies, so
    `hasDirectiveDependencies` is forced true and the full instruction
    set is emitted (`ɵɵelementStart`/`ɵɵelementEnd`).

This mode-dependent switch was previously only exercised incidentally by
the `foreign_component` case, which couples it with foreign-component
compilation. The new case isolates it.

(cherry picked from commit eb3e480360)
2026-07-21 11:06:41 +02:00
cexbrayat 70500e4067 fix(core): preserve explicit input transform write type
If a directive has an input declared as `dismissible = input<boolean>(true, {transform: booleanAttribute});` then the following templates were not compiling:

```
<div directiveName dismissible="true"></div>
<div directiveName dismissible></div>
```

This commit fixes the issue, without breaking contravariant consumers.

(cherry picked from commit 0ae6d81ed2)
2026-07-15 12:02:23 -07:00
Matthew Beck c82ae67e3d Revert "fix(core): allow static attributes for explicit input transforms"
This reverts commit 9b9b0e93c9.

This broke g3. Not sure yet why it didn't break externally. We can
investigate and fix following this revert.

(cherry picked from commit 1fb4678207)
2026-07-09 17:58:26 -07:00
cexbrayat 94d9591b51 fix(core): allow static attributes for explicit input transforms
This is a follow-up to #67997, which allowed explicit read generics with input transforms, such as `input<boolean>(false, {transform: booleanAttribute})`.

That fixed the declaration, but static template attributes like `dismissible="true"` and bare `dismissible` were still checked as strings against the read type. Allow the fallback write type to include static attribute strings so these template forms compile.

(cherry picked from commit 9b9b0e93c9)
2026-07-09 12:28:29 -07:00
P4 534fe81a89 fix(compiler-cli): apply debugName transform to required signal queries
Transform assumed `.required` functions always take options as the first argument.
This is true for `input` and `model`, but not for `viewChild` and `contentChild`,
which take the same arguments as non-required versions.

Change the code to put options for signal queries in the right position,
causing debugName to be correctly generated for signal queries.

(cherry picked from commit eb2a8ff63f)
2026-07-07 11:05:28 -07:00
Andrew Scott c3be83cfe1 refactor(core): allow AnimationClassBindingFn to return undefined or null
The AnimationClassBindingFn type was too restrictive, only allowing `string | string[]`. However, the runtime (`getClassListFromValue`) safely handles `undefined` and `null` values by treating them as no animation.

This change updates the type to allow `undefined` and `null`, which is consistent with other class/style bindings in Angular and avoids requiring workarounds (like empty strings) in host bindings.

Added a compliance test case to verify that `[animate.enter]` with a potentially `undefined` value compiles correctly.

(cherry picked from commit a7bde662c3)
2026-06-30 17:28:04 -07:00
Alex Rickabaugh af7edd90ca Revert "fix(compiler-cli): include toSignal in debugName transform"
This reverts commit 165995285c. Reason: breaking
in g3 (ngDevMode not defined)

(cherry picked from commit a5f1b20373)
2026-06-30 13:24:21 -07:00
Paweł Maniecki baf09a9939 fix(compiler-cli): include toSignal in debugName transform
the toSignal function received a debugName option in 0812ac3bec,
but was not covered by the signalMetadataTransform which sets the debugName in dev mode
automatically.

(cherry picked from commit 165995285c)
2026-06-29 14:32:22 -07:00
aparziale 06d854929c fix(compiler-cli): report diagnostic instead of crashing on malformed host binding
`parseHostBindings` throws plain `Error`s for malformed host bindings
(e.g. a property binding with a non-static value, as can happen while
editing in the language service). These were uncaught during directive
analysis, crashing the compiler and the Angular Language Service.

Wrap the call and surface the error as a `FatalDiagnosticError` so it
becomes a diagnostic and analysis can complete normally.

Fixes #69106

(cherry picked from commit 8b2785b597)
2026-06-24 12:14:27 -04:00
Alex Rickabaugh ffbbbf9129 refactor(compiler): add support for @Input transforms under isolatedDeclarations
Adds support for `@Input` transform functions in isolated declarations mode (`emitDeclarationOnly: true`), allowing components and directives to specify `transform` functions without triggering fatal compiler errors.

Synthesizes the `ngAcceptInputType_` write type syntactically:
- For referenced functions (`transform: booleanAttribute`), emits `Parameters<typeof booleanAttribute>[0]`, relying on downstream template type checking to resolve the type.
- For inline functions (`transform: (v: string) => boolean`), extracts `parameters[0].type` directly from the local TypeScript AST.

(cherry picked from commit 86ade07de6)
2026-06-16 17:27:23 +00:00
Alex Rickabaugh 568bd3a816 refactor(compiler): add support for host directives under isolatedDeclarations
Removes restrictions around using external references and local directives in `hostDirectives` under isolated declarations mode (`emitDeclarationOnly: true`).

By wrapping the host directive reference in a `WrappedNodeExpr`, TypeScript's declaration emitter seamlessly emits `typeof hostReference.node`, preserving existing imports or local identifiers exactly as authored. Also adds support for translating `PropertyAccessExpression` inside `WrappedNodeExpr` into `QualifiedName` for `.d.ts` emission, ensuring namespace imports (`import * as n from './dir'`) are preserved correctly.

(cherry picked from commit 5d2b1c4100)
2026-06-16 17:27:23 +00:00
SkyZeroZx b32ee7ceb3 fix(core): treat iframe credentialless as security-sensitive
Mark the iframe `credentialless` attribute as security-sensitive so dynamic
bindings are handled consistently with other iframe attributes that affect the
initial navigation, such as `sandbox`, `allow`, `referrerPolicy`, `csp`, and
`fetchPriority`.

Because `credentialless` must be present before the iframe starts loading to
affect the navigation’s credential mode, late dynamic updates can leave the final
DOM looking correct while the initial request was not loaded credentiallessly.

(cherry picked from commit 0152e3cbdf)
2026-06-16 16:05:57 +00:00
Andrew Scott be45e8e7cb refactor(compiler-cli): Change indexComponent file to be fileUrl
We do not need ParseSourceFile which contains the whole content. Only the file url is ever used.

(cherry picked from commit 21fccd4038)
2026-06-15 17:56:55 +00:00
Andrew Scott 06e9dbf9a5 refactor(core): ɵɵgetInheritedFactory should accept abstract type
An abstract component or directive can extend another class, meaning
ɵɵgetInheritedFactory needs to allow abstract

(cherry picked from commit 2112edefe1)
2026-06-15 16:22:39 +00:00
Andrew Scott 0f68807836 refactor(core): ComponentDef should allow abstract types too
d1539a8513 incorrectly assumed components wouldn't be abstract but
it is still possible (though probably should be an abstract directive instead).

(cherry picked from commit 8984c59626)
2026-06-11 20:08:13 +00:00
Andrew Scott 4b0c3b8b8f refactor(core): Update registerNgModuleType to support codegen typechecking
Updates types and adds test for source->source transformation with tsc downstream

(cherry picked from commit d25d2e1524)
2026-06-10 17:53:00 +00:00
Andrew Scott 01ea640539 refactor(core): Fix DirectiveDefinition interface to allow abstract classes
Interface should permit abstract classes since directives can be abstract

(cherry picked from commit d1539a8513)
2026-06-09 23:21:08 +00:00
SkyZeroZx 393b84caf8 fix(compiler): sanitize two-way properties
Apply schema-derived sanitizer resolution to TwoWayProperty ops so native two-way DOM bindings emit the same sanitizer as one-way property bindings.

Add compiler compliance coverage for innerHTML, srcdoc, URL, resource URL, and security-sensitive attribute cases.

(cherry picked from commit 3c70270c96)
2026-06-08 20:12:27 +00:00
Kristiyan Kostadinov a56f1cdf8f fix(compiler): more robust logic to check if regex can be optimized
Currently we only skip regex optimization if it has the `g` flag, however regexes can also have a state with the `y` flag.

These changes move to an allowlist model where we only optimize for a set of know flags.

(cherry picked from commit 636cc94105)
2026-06-03 18:53:41 +00:00
Kristiyan Kostadinov 2891f7e787 fix(compiler): move projection attributes into constants
We can save some memory by moving the `attrs` passed into the `projection` instruction into the constant pool.

(cherry picked from commit f0b28f6443)
2026-06-01 12:28:36 +02:00
Alex Rickabaugh 2200b4a854 refactor(compiler): add support for compiling NgModules under isolatedDeclarations
This commit adds support for compiling NgModules in isolated declarations mode.

(cherry picked from commit 06b004ec5c)
2026-05-22 14:00:23 -07:00
Alan Agius b2b8dea732 fix(compiler): strip namespaced SVG script elements during template compilation
Ensures that namespaced <script> elements (such as :svg:script) are correctly classified as PreparsedElementType.SCRIPT by the template preparser and stripped during compilation to prevent potential XSS vulnerabilities. Consequently, obsolete security schema mappings and runtime sanitization checks for <script> attributes have been removed since these elements are never present in compiled template outputs.

(cherry picked from commit 90494cd909)
2026-05-19 13:06:06 -07:00
Andrew Scott 1630d8f8e9 refactor(compiler-cli): Remove unused properties of IndexedComponent interface
These properties aren't used in the Kythe indexer and can be removed

(cherry picked from commit 13911b156b)
2026-05-15 10:38:03 -07:00
Kristiyan Kostadinov ccb7d427e4 fix(compiler): type check invalid for loops
Currently if a `@for` loop doesn't have a `track` expression we don't produce an AST for it at all which means no type checking and language service support for it.

These changes make it so we produce the AST anyways since it gives the user more tools to resolve the issue (e.g. autocompletion when writing the `track` expression).

(cherry picked from commit 06f6dec7aa)
2026-05-13 11:26:46 -07:00
Matthieu Riegler 78ec99d146 docs(docs-infra): improve api docs extraction
This allows us to show the API docs when the jsdoc block is at the top of a overloaded function (and not on the implementation signature).

eg: `injectAsync`
(cherry picked from commit 7360c1da68)
2026-05-11 12:03:44 -07:00
Leon Senft 1f30aacbe5 refactor(forms): bind formatted date string to min/max for minDate/maxDate (#68001)
* Test that `minDate`/`maxDate` binds to `min`/`max` on date and time inputs
* Test that `min`/`max` attribute can be set directly on date and time inputs
* Relax type checker to allow `min`/`max` bindings on date and time inputs

PR Close #68001
2026-05-06 11:59:18 -07:00
Kristiyan Kostadinov b225a5d902 fix(compiler): invalid type checking code if field name needs to be quoted
Fixes that we were producing invalid TypeScript if an input with an unsafe name (e.g. `aria-label`) is coerced.
2026-05-05 09:34:26 -07:00
Matthew Beck 0fa8f98f4f test: add NgModule compliance test with 'bootstrap' & local compilation
There was not a test demonstrating local compilation with the
'bootstrap' param on NgModule. This test adds one, among other NgModule
fields in one. These other fields are broadly covered already, but this
rolls them into one test exercising all fields.
2026-05-01 15:58:05 -07:00
SkyZeroZx 11721509b0 refactor(core): Makes @defer(hydrate ...) runtime tree-shakable
This commit updates `@defer` logic related to incremental hydration to be tree-shakable.

If hydrate triggers are used in a `@defer` block, the compiler emits a single top-level call to `ɵɵenableIncrementalHydrationRuntime`, placed once per create block before the first `ɵɵdefer` that requires it.

As a result, the incremental hydration runtime is only included in the bundle when hydrate is explicitly used.
2026-05-01 15:54:55 -07:00
Matthieu Riegler 2896c93cc1 feat(compiler): Angular expressions with optional chaining returns undefined
To mitigate this breaking change,  this behavior can be disabled by wrapping expressions with the `$null` magic function.
: `$null(foo?.bar?.baz)`
2026-04-28 15:26:53 -07:00
Kristiyan Kostadinov 72be5be9c1 refactor(compiler-cli): remove checkTwoWayBoundEvents flag
Removes the `checkTwoWayBoundEvents` flag since the code it generates is quite breaking and we never got the chance to enable it. Also it caused our tests to misrepresent how the compiler behaves for actual users.
2026-04-28 10:31:42 -07:00
Suraj Yadav 2c141c04cb refactor(compiler-cli): simplify Angular decorator stripping
Removes redundant decorator-stripping branches and consolidates
the transformation flow to reduce complexity and improve readability.
2026-04-22 11:07:35 -07:00
Kristiyan Kostadinov 8f3d0b9d97 feat(core): introduce @Service decorator
These changes introduce the new `@Service` decorator which is a more ergonomic alternative to `@Injectable`. The reason we're adding a new decorator is that `@Injectable` has been around since the beginning of Angular and it has a lot of baggage that adds unnecessary overhead for users that generally want to define a singleton service, available in their entire app. The key differences between `@Service` and `@Injectable` are:
1. `@Service` is `providedIn: 'root'` by default. You can opt into providing the service yourself by setting `autoProvided: false` on it.
2. `@Service` doesn't allow constructor-based injection, only the `inject` function.
3. `@Service` doesn't support the complex type signature of `@Injectable` (`useClass`, `useValue` etc.). Instead it supports a single `factory` function.

Example:

```ts
import {Service} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {AuthService} from './auth';

@Service()
export class PostService {
  private readonly httpClient = inject(HttpClient);
  private readonly authService = inject(AuthService);

  getUserPosts() {
    return this.httpClient.get('/api/posts/' + this.authService.userId);
  }
}
```
2026-04-22 11:01:01 -07:00
Kristiyan Kostadinov e5f96c2d88 fix(compiler-cli): animation events not type checked properly when bound through HostListener decorator
Fixes that we weren't inferring the type of `animate.` event correctly, if they're bound through a `@HostListener` decorator.
2026-04-13 11:05:16 +03:00
Matthew Beck 2c5aabb9da fix(compiler): don't escape dollar sign in literal expression
Removes the escape for `$` in literal expressions. I don't think this is
required with our output.
2026-04-10 09:23:50 +03:00
Matthieu Riegler 47fcbc4704 feat(compiler): allow safe navigation to correctly narrow down nullables
The commit updates the TCB for safe navigation expressions to allow for correct narrowing of nullables.

This will trigger the `nullishCoalescingNotNullable` and `optionalChainNotNullable` diagnostics on exisiting projects.
You might want to disable those 2 diagnotiscs in your `tsconfig` temporarily if you want to update your project without having to fix all the issues at once.

Narrowing can be disabled altogether with `strictSafeNavigationTyes: false`.

fixes #37619

BREAKING CHANGE: This change will trigger the `nullishCoalescingNotNullable` and `optionalChainNotNullable` diagnostics on exisiting projects.
You might want to disable those 2 diagnotiscs in your `tsconfig` temporarily.
2026-04-09 18:26:08 +03:00
Kristiyan Kostadinov ab061a7610 fix(compiler-cli): error for type parameter declarations
Fixes an error that was heppning when a generic param has type parameters of its own. There were a few different issues going on:
1. In #67707 I had changed a bit how we pass the `genericContextBehavior` which ended up ignoring the `useContextGenericType` option from the environment.
2. All directives depend on themselves, but we were overridding the `genericContextBehavior` for the directive being processed.
3. The type translator wasn't handling type parameter declarations. Technically we shouldn't be able to hit a code path that has a type parameter, however it's also easy enough to handle so we might as well.

Relates to #67704.
2026-04-07 09:29:29 -07:00
Kristiyan Kostadinov 2ce0e98f79 fix(compiler): handle nested brackets in host object bindings
Fixes that we were parsing bindings in the `host` object with a regex that didn't account for nested brackets which may come up with something like Tailwind.

Fixes #68039.
2026-04-06 13:21:50 -07:00
Kristiyan Kostadinov fd95735594 refactor(compiler-cli): fix failing tests
Fixes some tests that started failing after recent changes.
2026-04-06 12:33:05 -07:00
Matthieu Riegler f3c471e0d5 refactor(compiler): remove fullTemplateTypeCheck compiler option.
The option was deprecated back in v13. Users should use `strictTemplates: true`.
2026-04-06 11:55:09 -07:00
Kristiyan Kostadinov 57432f1b6a refactor(compiler-cli): merge duplicate directive matches and report conflicts
Implements the logic at the compiler level that will de-duplicate host directives and merge them together. It will also report if a conflict is detected during merging.
2026-04-03 09:44:39 -07:00
Andrei Chmelev fcd0bb0db8 fix(compiler-cli): prevent recursive scope checks for invalid NgModule imports
Avoid recursive local scope lookups when invalid NgModule imports create import cycles.
2026-03-27 16:10:01 +01:00
Matthieu Riegler eae8f7e30b feat(core): Set default Component changeDetection strategy to OnPush
The default change detection strategy is now OnPush.

BREAKING CHANGE: Component with undefined `changeDetection` property are now `OnPush` by default. Specify `changeDetection: ChangeDetectionStrategy.Eager` to keep the previous behavior.
2026-03-24 16:25:02 -07:00
Matthieu Riegler f46e8bd440 refactor(compiler): remove fullTemplateTypeCheck compiler option.
The option was deprecated back in v13. Users should use `strictTemplates: true`.
2026-03-23 11:33:15 -07:00
Kristiyan Kostadinov 63ac1bd2fd refactor(compiler-cli): decouple host element creation logic from TypeScript
Reworks the logic for constructing a `HostElement` node so that we can reuse it without depending on TypeScript APIs.
2026-03-23 11:16:39 -07:00
SkyZeroZx ca67828ee2 refactor(compiler-cli): introduce NG8023 compile-time diagnostic for duplicate selectors
Add NG8023 extended diagnostic to report duplicate component selectors
during compilation.

This replaces the former NG0300 runtime error, ensuring the failure
occurs at build time instead of runtime.

Closes  angular#48377

BREAKING CHANGE: Elements with multiple matching selectors will now throw at compile time.
2026-03-19 16:12:02 -07:00
Alex Rickabaugh 41b1410cb8 feat(forms): support binding number|null to <input type="text">
`<input type="number">` often does not provide the desired user experience when editing numbers in
a form. MDN even [describes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input/number#using_number_inputs)
how text inputs should be used in many cases instead, via `<input type="text" inputmode="numeric">`
or similar configurations. Previously, this did not work with Signal Forms without a custom input
component/directive.

This PR builds support for binding `number|null` models directly to `<input type="text">` native
controls via `[formField]`. When a model has a number or `null` value, signal forms will preserve
that status when the user makes edits/changes. Empty string values are converted to `null`, other
values are parsed as numbers, and a parse error is raised when a non-numeric value is entered.

Note that it's up to the UI developer to configure additional UI affordances such as setting an
appropriate `inputmode`, rejecting non-numeric keypresses, etc.

Fixes #66903
Fixes #66157
2026-03-19 15:26:34 -07:00