Skip to content

bug: undetected initial prop value on Angular #6373

Description

@mamillastre

Prerequisites

Stencil Version

=4.36.0

Current Behavior

Since Stencil 4.36.0, an initial prop value can be undetected on a dynamically set Angular component.

For example, I use the following code to emulate the dynamic first prop value:

<my-component [first]="'issue'"></my-component>

I have the following logs:

@Prop() first!: string;
@Watch('first')
firstChanged() {
  console.log('CHANGE', this.first);
}

connectedCallback() {
  console.log('connectedCallback', this.first);
}

componentWillLoad() {
  console.log('componentWillLoad', this.first);
}

componentDidLoad() {
  console.log('componentDidLoad', this.first);
}

render() {
  console.log('render', this.first);
  ...
}

In runtime:

Image

The value comes only at the second rendering, the prop has not been initialized before componentWillLoad and the Watch() method has not been called.
The prop update seems to be undetected but fire a rerender.

Note: I reproduced this issue only when the component is on a child routing page and when the app is loaded on this page (See reproduction steps).

Expected Behavior

The prop is available on componentWillLoad OR the Watch() method is called.

System Info

System: node 20.18.3
Platform: darwin (24.6.0)
CPU Model: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz (12 cpus)
Compiler: /stencil-demo/packages/elements/node_modules/@stencil/core/compiler/stencil.js
Build: 1752598220
Stencil: 4.36.0 🎊
TypeScript: 5.5.4
Rollup: 4.34.9
Parse5: 7.2.1
jQuery: 4.0.0-pre
Terser: 5.37.0

Steps to Reproduce

Image
  • Refresh the page (on the test page)
  • The Watch() method is not called
Image

If the stencil component is in the Angular root component (projects/angular-app/src/app/app.component.html), the prop is initialized on componentWillLoad.

Image

Code Reproduction URL

https://github.com/mamillastre/stencil-demo/tree/angular-issue

Additional Information

The issue seems to come from Stencil v3.36.0.
Workaround: stay on the v3.35.3
I didn't try to reproduce on Vue or React.

Activity

  1. johnjenkins commented on Aug 22, 2025

    @johnjenkins
    Contributor

    @danielleroux I'm pretty sure this is due to #6331 < do you have any insights?
    (@mamillastre I believe this stems from Stencil components now rendering much faster - perhaps Angular sets properties too slowly)

  2. added
    Bug: Validated
    on Aug 22, 2025
  3. danielleroux commented on Aug 22, 2025

    @danielleroux
    Contributor

    @johnjenkins cannot reproduce the issue on our setup:

    @siemens/ix:build: [55:51.9] @stencil/core
    @siemens/ix:build: [55:52.0] v4.36.0 🎊

    Image

    Also tested with v4.36.2 and angular 20

    @mamillastre Maybe you can try to reproduce it based on the output-target repo.

  4. ben-hamida commented on Aug 22, 2025

    @ben-hamida

    We're having a similar issue where in one particular place in our app componentWillLoad is called before the angular input has been set. We have other places with almost identical code using the same stencil component where it doesn't happen.

  5. mamillastre commented on Aug 25, 2025

    @mamillastre
    Author

    (@mamillastre I believe this stems from Stencil components now rendering much faster - perhaps Angular sets properties too slowly)

    It can be the issue. But in this case, the @Watch() method should be called when the Angular value is initialized.

    @johnjenkins cannot reproduce the issue on our setup:

    @siemens/ix:build: [55:51.9] @stencil/core
    @siemens/ix:build: [55:52.0] v4.36.0 🎊

    Image Also tested with v4.36.2 and angular 20

    @mamillastre Maybe you can try to reproduce it based on the output-target repo.

    Do you reproduce on my repo ? https://github.com/mamillastre/stencil-demo/tree/angular-issue

  6. danielleroux commented on Aug 25, 2025

    @danielleroux
    Contributor

    (@mamillastre I believe this stems from Stencil components now rendering much faster - perhaps Angular sets properties too slowly)

    It can be the issue. But in this case, the @Watch() method should be called when the Angular value is initialized.

    @johnjenkins cannot reproduce the issue on our setup:

    @siemens/ix:build: [55:51.9] @stencil/core
    @siemens/ix:build: [55:52.0] v4.36.0 🎊

    Image Also tested with v4.36.2 and angular 20 [@mamillastre](https://github.com/mamillastre) Maybe you can try to reproduce it based on the output-target repo.

    Do you reproduce on my repo ? https://github.com/mamillastre/stencil-demo/tree/angular-issue

    No there is to much stuff in there, I do not install any repo without knowing which dependencies in there. I would suggest use stencil/output-target fork to make a repo to show the issue.

  7. johnjenkins commented on Aug 25, 2025

    @johnjenkins
    Contributor

    It does seem to be an issue; Ionic users have also reported it: ionic-team/ionic-framework#30613

  8. mamillastre commented on Aug 25, 2025

    @mamillastre
    Author

    @danielleroux, I forked the output-target repo and reproduced this issue in the issue-angular-prop-init branch: https://github.com/mamillastre/output-targets/tree/issue-angular-prop-init
    Here is the commit detail: mamillastre/output-targets@358112c

  9. danielleroux commented on Aug 25, 2025

    @danielleroux
    Contributor

    @johnjenkins Do we have any angular dev's here who have some insights into change detection etc? The regular task queue uses requestAnimationFrame which works like desired.

    The issue only happens with queueMicrotask. Same as providing taskQueue: 'immediate', inside the stencil.config.ts even without the changes of the queueMicrotask.

    //Edit

    Maybe a possible fix would be to put the lifecycle calls back into the event loop of the repaint frames.

    export const safeCall = (instance: any, method: string, arg?: any, elm?: HTMLElement) => {
      if (instance && instance[method]) {
        try {
          return new Promise<void>((resolve) => {
            plt.raf(() => resolve(instance[method](arg)));
          });
        } catch (e) {
          consoleError(e, elm);
        }
      }
      return undefined;
    };

    //Edit 2

    It looks promising If I put the lifecycle calls back into the repaint loop, but keep the initial rendering inside the microtask-loop.

  10. johnjenkins commented on Sep 5, 2025

    @johnjenkins
    Contributor

    Do we have any angular dev's here who have some insights into change detection etc? The regular task queue uses requestAnimationFrame which works like desired.

    @gratzl-dev maybe?

  11. danielleroux commented on Sep 5, 2025

    @danielleroux
    Contributor

    I dont have a solution right now. My current assumption is:

    Actual issue:
    Image

    1. lifecycle calls and initial rendering is called via queueMicrotask (safe time prior to control returning to the browser's event loop.)
    2. lifecycle result: valueA = undefined
    3. Angular try to perform the angular bindings `[value-a]="'demo'"
      ==> render dependent lifecycle functions will be execute before angular performs the binding

    Putting lifecycle calls into requestAnimationFrame will not solve the issue:
    Image

    1. initial rendering is called still via queueMicrotask
    2. Angular try to perform the angular bindings `[value-a]="'demo'"
    3. lifecycle calls are executed during requestAnimationFrame loop
    4. lifecycle result `valueA = 'demo'

    ==> Problem componentWillRender and componentWillLoad has the following feature A promise can be returned, that can be used to wait for the upcoming render. This does not work for the initial rendering attempt.

    Note: Graphics are super simplified and does not show 100% the execution order or architecture of stencil/angular. Theres are just my assumption of the issue. (Iam still no angular guy to understand every render detail there)

    Solutions what I have in mind is, but not sure about:

    • Make the queue configuration part of the @Component-decorator or event a runtime flag. Stencil developers can decide If they need the "faster-initial-rendering" or "controlled-rendering" behaviour.
  12. johnjenkins commented on Sep 5, 2025

    @johnjenkins
    Contributor

    @danielleroux did you try adjusting the taskQueue option before your PR?
    It is (or was?) async, perhaps you just wanted immediate and we can revert? idk - haven't looked much into it

  13. johnjenkins commented on Sep 5, 2025

    @johnjenkins
    Contributor

    @danielleroux / @mamillastre - I've just noticed this hidden in Stencil's docs too ...

    /**

    • When a component is first attached to the DOM, this setting will wait a single tick before
    • rendering. This works around an Angular issue, where Angular attaches the elements before
    • settings their initial state, leading to double renders and unnecessary event dispatches.
    • Defaults to false.
      */
      initializeNextTick?: boolean;

    sounds relevant ... can someone experiment?

  14. danielleroux commented on Sep 8, 2025

    @danielleroux
    Contributor

    @danielleroux did you try adjusting the taskQueue option before your PR? It is (or was?) async, perhaps you just wanted immediate and we can revert? idk - haven't looked much into it

    I dont think so because applying updates makes totally sense to do that only depending on the refresh rate and the initial render before the browser frame is shown.
    If you look at the if-branch of the initializeNextTick there are two closed angular tickets.

  15. 7 remaining items

  16. johnjenkins commented on Sep 11, 2025

    @johnjenkins
    Contributor

    awesome - thanks for the investigation @kristilw

  17. mamillastre commented on Sep 23, 2025

    @mamillastre
    Author

    Hi @johnjenkins, the commit has been reverted on 4.37.1
    Does fix issue is still fixed ?

  18. johnjenkins commented on Sep 23, 2025

    @johnjenkins
    Contributor

    yep @mamillastre - re-opened

  19. johnjenkins commented on Sep 23, 2025

    @johnjenkins
    Contributor

    however - this particular issue / repro is fixed or rather has consistent workarounds now.

    per component:

    async componentWillLoad() {
        return new Promise<void>((resolve) => {
          requestAnimationFrame(() => {
            console.log('componentWillLoad', this.first);
            resolve();
          });
        });
      }

    or globally, via extras.initializeNextTick

  20. mamillastre commented on Sep 23, 2025

    @mamillastre
    Author

    Even with the workarounds, I think that this is still a breaking change between the 4.35 and 4.36 versions.

    The per component solution does not feel right since we have to remember to add this piece of code. The issue happens in particular cases, so it's easy to forget.

    I am not familiar with the initializeNextTick extras configuration. I do not find it in the documentation. What is the impact of using this option?
    You quote this documentation that concerns me: settings their initial state, leading to double renders and unnecessary event dispatches.

    Does the Ionic framework will not be impacted by this issue?

    Thank you

  21. johnjenkins commented on Sep 23, 2025

    @johnjenkins
    Contributor

    Even with the workarounds, I think that this is still a breaking change between the 4.35 and 4.36 versions.

    The change between those versions is Stencil got much faster in initialising it's components - esp in the dist-custom-elements output - due to @danielleroux work.

    Angular has an issue in that it attaches your components to the DOM then binds it's dynamic properties (e.g. yourElemen.prop1 = boundProp) < Stencil has already done it's first render - this is the reason for this new behaviour.

    I am not familiar with the initializeNextTick extras configuration. I do not find it in the documentation. What is the impact of using this option?

    There is no documentation for it (I guess as it's a hack for a niche, Angular-only buggy behaviour) - here's the declaration description in context - https://github.com/stenciljs/core/blob/main/src/declarations/stencil-public-compiler.ts#L369

    Turning it to true will essentially recreate the old behaviour; throttling a components' initial render so Angular has had time to attach it's bound property. No more 'double renders' / watchers firing when the initial property is added.

    This new behaviour won't be rolled back as I think the best default is for components to render ASAP.

    We will be looking at watcher attaching though to make it more consistent.

    Hope that all makes sense!

  22. mamillastre commented on Sep 23, 2025

    @mamillastre
    Author

    Thank you very much @johnjenkins for the explanations.

    I will use the workarounds for now, waiting for the watcher fix 👍

  23. pfteter commented on Oct 20, 2025

    @pfteter
    Contributor

    preact switched back to requestAnimationFrame from queueMicrotask because of stability issues, there is a whole section in angular core about it why they still use requestAnimationFrame.
    Did you try to switch from queueMicrotask back to requestAnimationFrame in stencil to see if the issue still happens ?

  24. pfteter commented on Oct 20, 2025

    @pfteter
    Contributor

    https://github.com/angular/angular/blob/c60ab336c9e862f6fc3b16cab4a8b2dd910712cf/packages/core/src/util/callback_scheduler.ts#L13

    what angular is saying about it:

    Both `setTimeout` and `rAF` are able to "coalesce" several events from a single user
     * interaction into a single change detection. Importantly, this reduces view tree traversals when
     * compared to an alternative timing mechanism like `queueMicrotask`, where change detection would
     * then be interleaves between each event.
    
  25. johnjenkins commented on Oct 20, 2025

    @johnjenkins
    Contributor

    Experimentation / PRs most welcome!

    RAF is still used for the majority of updating (if taskQueue is not set to immediate); queueMicrotask is only used for the first, initial render.

  26. Cliffback commented on Nov 20, 2025

    @Cliffback
    Contributor

    however - this particular issue / repro is fixed or rather has consistent workarounds now.

    per component:

    async componentWillLoad() {
    return new Promise((resolve) => {
    requestAnimationFrame(() => {
    console.log('componentWillLoad', this.first);
    resolve();
    });
    });
    }
    or globally, via extras.initializeNextTick

    setting extras.initializeNextTick didn't work for us, while wrapping in a RAF promise did the job. Would have preferred to use the initializeNextTick option though

  27. Cliffback commented on Nov 24, 2025

    @Cliffback
    Contributor

    For tests that expects to throw, the suggested solution didn't work, so had to add a reject.

    async componentWillLoad(): Promise<void> {
        return new Promise<void>((resolve: () => void, reject: (error: Error) => void) => {
          requestAnimationFrame(() => {
            try {
              this.validateMin(this.min);
              this.validateMax(this.max);
              this.valuePropSet(this.value);
              const date = this.selectedCalendarDate ?? CalendarDate.now().fitConstraint(this.constraint);
              this.dropdownCalendar = date?.calendarMonth;
              resolve();
            } catch (e) {
              reject(e as Error);
            }
          });
        });
      }

    and change the test from this:

          it('value < min', async () => {
            return expect(async () => {
              await renderSpecPage(`<my-date-picker value="2000-01-01" min="${minDate}" max="${maxDate}"></my-date-picker>`);
            }).rejects.toThrow();
          });

    to this:

          it('value < min', async () => {
            try {
              await renderSpecPage(`<my-date-picker value="2000-01-01" min="${minDate}" max="${maxDate}"></my-date-picker>`);
              fail('Expected renderSpecPage to throw, but it resolved');
            } catch (e) {
              const message = e instanceof Error ? e?.message : String(e);
              expect(message).toContain('prop is either larger than max date or smaller than min date');
            }
          });

    Also wrote a TS AST Transformer to automate this. Hope it can save someone else time.

    It can be run with find path/to/look/for/components -name '*.tsx' | xargs -n 1 npx tsx path/to/script/transform-component WillLoad.ts

    transform-componentWillLoad.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Bug: ValidatedHas WorkaroundHelp Wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions