Skip to content

Creating a view inside an effect will track any signal reads that happen in the view #54548

Closed

Description

@kfrancois

Which @angular/* package(s) are the source of the bug?

Don't known / other

Is this a regression?

No

Description

I have a PopoverDirective which contains an input that allows the developer to pass in a custom template. It works like this:

<div
  appPopover
  [isPopoverVisible]="isPopoverVisible()"
  [popoverTemplate]="popoverTemplate"
>
   Regular content here
</div>

<ng-template #popoverTemplate> Popover content here </ng-template>

Internally, this directive fill open or destroy the popover depending on the isPopoverVisible input:

effect(() => {
  if (this.isPopoverVisible()) {
    this.openPopover();
  } else {
    this.destroyPopover();
  }
});

This works welll, but when adding signals into the popoverTemplate I notice that any effects contained inside the appPopover directive will fire again. Even if none of the directive's inputs have changed.

For example:

<div
  appPopover
  [isPopoverVisible]="isPopoverVisible()"
  [popoverTemplate]="popoverTemplate"
>
   Regular content here
</div>

<ng-template #popoverTemplate> {{ someSignal() }} </ng-template>

When someSignal changes, my effect inside the appPopover directive will now fire again, even though none of its inputs have changed (only the input of the template we pass in has changed).

This feels unintentional, I'd like to know if this is intended behaviour, or a bug in the framework.

Please provide a link to a minimal reproduction of the bug

https://github.com/kfrancois/angular-effects-repro

Also available in Stackblitz: https://stackblitz.com/github/kfrancois/angular-effects-repro

Please provide the exception or error you saw

Using the above link, follow these steps:

  1. Open the console
  2. Click on the Show popover button
  3. Click on the Do async logic to populate popover template button
  4. Observe the console output

On the "working" example, isPopoverVisible: true does not log twice.
On the "broken" example, isPopoverVisible: true does log twice, which is unexpected.

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 17.2.0
Node: 21.6.1 (Unsupported)
Package Manager: npm 10.4.0
OS: darwin arm64

Angular: 17.2.1

Anything else?

No response

Activity

  1. added
    area: core
    core: reactivity
    on Feb 21, 2024
  2. added this to the needsTriage milestone on Feb 21, 2024
  3. atscott commented on Feb 21, 2024

    @atscott
    Contributor

    This is working as expected. openPopover executes the popover template inside the effect which adds any signals in the template to the effect. You need to wrap openPopover inside an untracked call to prevent this: https://stackblitz.com/edit/github-kphkvx?file=src%2Fmain.ts,src%2Fapp%2Fbroken-popover.component.ts,src%2Fapp%2Fpopover-directive.ts,src%2Fapp%2Fworking-popover.component.ts

  4. reopened this on Feb 21, 2024
  5. alxhub commented on Feb 21, 2024

    @alxhub
    Member

    Note that this isn't exactly as expected - one of the reasons effect is still developer preview is that its interaction with different framework APIs is still a work in progress. In particular, it's an open question whether Angular should untrack all rendering operations by default, or throw errors if you accidentally call them from reactive contexts, or just run the operations like it does today.

  6. changed the title [-]Effects fire multiple times when input TemplateRef contains signals[/-] [+]Creating a view inside an `effect` will track any signal reads that happen in the view[/+] on Feb 21, 2024
  7. kfrancois commented on Feb 21, 2024

    @kfrancois
    Author

    Understood! Thank you Andrew & Alex for providing a workaround, and for providing feedback on this issue. 😄 🙏

    Glad to work with the current behaviour for the time being, since as you mentioned effect is in dev preview.

    My personal feeling is that the current behaviour is unexpected as it adds a hard to debug pitfall that's not immediately noticeable (IE: devs expect effects callbacks only to run when a tracked signal changes).

    The other options you mentioned both sound like valid paths to me (I'm curious about other developers' experience/opinions around either). Excited to follow along. 😄

    Feel free to repurpose/close this issue as desired!

  8. kfrancois commented on Feb 21, 2024

    @kfrancois
    Author

    tl;dr for anyone following along:

    When creating a view (e.g. through CDK Overlay) inside an effect function, this effect function will track any signals inside the created view.

    The current solution is to create this view inside an untracked(() => { ... }) function:

    // Template passed into a view that will be instantiated
    <ng-template #templateRef>
       {{ someSignal() }}
    </ng-template>
    
    
    // Effect that either instantiates or destroys the view
    createViewEffect = effect(() => {
      if (this.isPopoverVisible()) {
    
        // When wrapping with `untracked`, we ensure that this effect does not track signals inside the view
        untracked(() => this.openPopover());
      } else {
        this.destroyPopover();
      }
    });
    
    openPopover() {
      const templateRef = this.templateRef();
    
      // Create an embedded view using this template
      ...
    }
  9. mikezks commented on Feb 22, 2024

    @mikezks

    I would prefer error and opt-in through options flag like with allowSignalWrites.

    Same would be good if someone calls an Output-EventEmitter inside an effect().

  10. markostanimirovic commented on Feb 23, 2024

    @markostanimirovic
    Contributor

    This is a good example of why the team should consider introducing an additional effect signature or another function named differently (e.g. watch) that provides the ability to specify dependencies explicitly and does not track the effect callback execution. Implicit dependency tracking looks nice and powerful, but when it comes to more complex cases, an explicit array/sequence of dependencies seems 'safer' and more predictable:

    watch(this.isPopoverVisible, (isVisible) => {
      if (isVisible) {
        this.openPopover();
      } else {
        this.destroyPopover();
      }
    });

    Btw, VueJS provides both options via watch (explicit) and watchEffect (implicit dependency tracking) functions.

  11. added a commit that references this issue on Feb 29, 2024
    ffbafc7
  12. added a commit that references this issue on Feb 29, 2024
    ffad7b8
  13. angular-automatic-lock-bot commented on Mar 31, 2024

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  14. locked and limited conversation to collaborators on Mar 31, 2024
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

    area: corecore: reactivitycross-cutting: signals

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions