Skip to content

unintended duplicate imports can cause rendering error in standalone component life cycle. #46109

Closed

Description

@leo6104

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

compiler-cli, compiler, core

Is this a regression?

No

Description

@Component({
   template: `
    <mat-form-field>
      <input matInput [matDatepicker]="picker">
      <mat-datepicker #picker [startAt]="startAt"></mat-datepicker>
    </mat-form-field>
   `,
   standalone: true,
   imports: [
      MatFormFieldModule, // It caused mat-form-field initializing error.
      MatInputModule,
      MatDatepickerModule,
   ],
})
export class StandaloneComponent {
   @ViewChild(MatDatepicker, { static: true }) picker: MatDatepicker<any>;
   startAt = new Date(); 
}

Developer expect that cause i use mat-form-field matInput directive so put MatFormFieldModule, MatInputModule in standalone component imports. But, it can cause an error for now. When i remove MatFormFieldModule in StandaloneComponent.imports, it doesn't occur errors. The reason is that MatInputModule already import-export MatFormFieldModule. It seems angular life-cycle handler trigger without duplicate check. Developers cannot consider all module+component dependencies when they use 3rd party library (it can be changed in the future).

It is not only NgModule-only problem in standalone component. I found it can be caused by duplicate imports of Component / NgModule both case.

Duplicate component imports can cause error too.

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

instrument.js:109 ERROR TypeError: Cannot set properties of undefined (setting 'ngIf')
    at setInputsForProperty (core.mjs:13015:13)
    at elementPropertyInternal (core.mjs:12026:9)
    at Module.ɵɵproperty (core.mjs:14906:9)
    at MatFormField_Template (form-field.mjs:683:3057)
    at executeTemplate (core.mjs:11621:9)
    at refreshView (core.mjs:11484:13)
    at detectChangesInternal (core.mjs:12873:9)
    at ViewRef$1.detectChanges (core.mjs:21935:9)
    at MatFormField.ngAfterViewInit (form-field.mjs:460:33)
    at callHook (core.mjs:2576:22)
    at callHooks (core.mjs:2545:17)
    at executeInitAndCheckHooks (core.mjs:2496:9)
    at refreshView (core.mjs:11555:21)
    at refreshComponent (core.mjs:12688:13)
    at refreshChildComponents (core.mjs:11274:9)
    at refreshView (core.mjs:11534:13)
    at renderComponentOrTemplate (core.mjs:11601:9)
    at tickRootContext (core.mjs:12864:13)
    at detectChangesInRootView (core.mjs:12890:5)
    at RootViewRef.detectChanges (core.mjs:21974:9)
    at ComponentLoader.show (ngx-bootstrap-component-loader.mjs:125:65)
    at BsModalService._showModal (mapiacompany-ngx-bootstrap-modal.mjs:500:1)
    at BsModalService.show (mapiacompany-ngx-bootstrap-modal.mjs:378:1)
    at TagEditModalComponent.openTagFeaturedModal (tag-edit-modal.component.ts:537:35)
    at TagEditModalComponent_div_2_mp_button_3_Template_mp_button_click_0_listener (template.html:34:9)
    at executeListenerWithErrorHandling (core.mjs:15474:16)
    at wrapListenerIn_markDirtyAndPreventDefault (core.mjs:15509:22)
    at HTMLElement.<anonymous> (platform-browser.mjs:459:38)
    at HTMLElement.sentryWrapped (helpers.js:74:23)
    at _ZoneDelegate.invokeTask (zone.js:406:1)
    at Object.onInvokeTask (core.mjs:26304:33)
    at _ZoneDelegate.invokeTask (zone.js:405:1)
    at Zone.runTask (zone.js:178:1)
    at ZoneTask.invokeTask [as invoke] (zone.js:487:1)
    at invokeTask (zone.js:1648:1)
    at globalCallback (zone.js:1691:1)
    at HTMLElement.globalZoneAwareCallback (zone.js:1712:1)

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

Angular CLI: 14.0.0-rc.1
Node: 16.14.2
Package Manager: npm 8.5.0 
OS: darwin x64

Angular: 14.0.0-rc.1
... animations, bazel, cli, common, compiler, compiler-cli, core
... forms, localize, platform-browser, platform-browser-dynamic
... platform-server, router, service-worker

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1400.0-rc.1
@angular-devkit/build-angular   14.0.0-rc.1
@angular-devkit/core            14.0.0-rc.1
@angular-devkit/schematics      14.0.0-rc.1
@angular/cdk                    14.0.0-rc.0
@angular/material               14.0.0-rc.0
@angular/youtube-player         13.3.1
@nguniversal/common             13.1.1
@schematics/angular             14.0.0-rc.1
ng-packagr                      14.0.0-rc.0
rxjs                            7.5.5
typescript                      4.6.4

Anything else?

We use ngx-bootstrap modal to open these standalone component.

 show(opts = {}) {
        ... 
        if (!this._componentRef) {
            this._componentRef = this._componentFactory.create(injector, this._contentRef.nodes);
            this._applicationRef.attachView(this._componentRef.hostView);
            ... 
            
            if (this._contentRef.componentRef) {
                this._innerComponent = this._contentRef.componentRef.instance;
                this._contentRef.componentRef.changeDetectorRef.markForCheck();
                this._contentRef.componentRef.changeDetectorRef.detectChanges(); // Here is error state. 
            }

            this._componentRef.changeDetectorRef.markForCheck();
            this._componentRef.changeDetectorRef.detectChanges();
        }
        ...
        return this._componentRef;
    }

Activity

  1. changed the title [-]unintented duplicate imports can cause ngOnInit / ngOnDestory error in component life cycle.[/-] [+]unintended duplicate imports can cause ngOnInit / ngOnDestroy error in standalone component life cycle.[/+] on May 23, 2022
  2. changed the title [-]unintended duplicate imports can cause ngOnInit / ngOnDestroy error in standalone component life cycle.[/-] [+]unintended duplicate imports can cause rendering error in standalone component life cycle.[/+] on May 23, 2022
  3. pkozlowski-opensource commented on May 23, 2022

    @pkozlowski-opensource
    Member

    Would you mind sharing a minimal reproduce scenario? I think that something else is going on as I did use a standalone components with the exact list of imports you've mentioned. So I'm suspecting that ngx-bootstrap modal is a root cause / contributing factor here.

    In any case we really do nee a minimal reproduce scenario.

  4. added
    needs reproduction
    cross-cutting: standalone
    on May 23, 2022
  5. added
    area: core
    on May 23, 2022
  6. added this to the Backlog milestone on May 23, 2022
  7. pkozlowski-opensource commented on May 27, 2022

    @pkozlowski-opensource
    Member

    @leo6104 I was trying to reproduce the issue, in both the regular usage in a template and dynamic instantiation scenarios. Here are my attempts: https://stackblitz.com/edit/angular-standalone-4r1ubq?file=src%2Fmain.ts,package.json

    I wasn't able to see the error given the above setup. Given this and the fact that I haven't heard back from you with the exact reproduce scenario - we can't progress on this issue.

    Can you extract a minimal reproduce scenario to a stackblitz and share it here? If not we will have no choice but to close this issue.

  8. leo6104 commented on May 28, 2022

    @leo6104
    ContributorAuthor

    @pkozlowski-opensource Sorry for late comment. I was busy on working day.
    I also try to reproduce in stackblitz but it seems doesn't reproduce in that case.

    I guess we load standalone component dynamically

    import ('../tag-featured-modal/tag-featured-modal.component')
       .then(c => c.TagFeaturedModal)
       .then(component => this.modal.show(component) 
    

    I'm trying to reproducing the error with dynamic import case.

  9. pkozlowski-opensource commented on May 28, 2022

    @pkozlowski-opensource
    Member

    @leo6104 lazy-loading should not change the equation: https://stackblitz.com/edit/angular-standalone-wshpc1?file=src%2Fmain.ts,src%2Fapp%2Flazy.ts

    There must be something else going on but it is impossible to say what without a reproduce scenario.

  10. alxhub commented on Jun 6, 2022

    @alxhub
    Member

    This could be an AOT compiler issue that doesn't reproduce in Stackblitz

  11. leo6104 commented on Jun 11, 2022

    @leo6104
    ContributorAuthor

    I cannot reproduce in any case but in my project it still exists.
    I saw 131d029 commit and i expect that it will make the error message difference. I will check on next update again.

  12. t-bowersox commented on Jun 20, 2022

    @t-bowersox
    Contributor

    I think I might have encountered this issue, as well -- but only when I run unit tests. I had a component set up like so:

    import { CommonModule } from '@angular/common';
    import { Component, OnInit } from '@angular/core';
    import {
      FormControl,
      FormGroup,
      ReactiveFormsModule,
      Validators,
    } from '@angular/forms';
    import { MatButtonModule } from '@angular/material/button';
    import { MatFormFieldModule } from '@angular/material/form-field';
    import { MatInputModule } from '@angular/material/input';
    import { enterLeaveFade } from 'src/lib/animations/enterLeaveFade';
    
    @Component({
      selector: 'app-signup',
      standalone: true,
      imports: [
        CommonModule,
        ReactiveFormsModule,
        MatFormFieldModule,
        MatInputModule,
        MatButtonModule,
      ],
      templateUrl: './signup.component.html',
      styleUrls: ['./signup.component.scss'],
      animations: [enterLeaveFade],
    })
    export class SignupComponent implements OnInit {
      //...
    }

    And it's default test spec (I hadn't modified it yet):

    import { ComponentFixture, TestBed } from '@angular/core/testing';
    
    import { SignupComponent } from './signup.component';
    
    describe('SignupComponent', () => {
      let component: SignupComponent;
      let fixture: ComponentFixture<SignupComponent>;
    
      beforeEach(async () => {
        await TestBed.configureTestingModule({
          imports: [ SignupComponent ]
        })
        .compileComponents();
    
        fixture = TestBed.createComponent(SignupComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    });

    Running that spec yielded:

    Chrome 102.0.5005.115 (Mac OS 10.15.7) SignupComponent should create FAILED
            Error: NG0300: Multiple components match node with tagname mat-form-field: MatFormField and MatFormField. Find more at https://angular.io/errors/NG0300
            error properties: Object({ code: -300 })
                at throwMultipleComponentError (node_modules/@angular/core/fesm2020/core.mjs:6962:11)
                at findDirectiveDefMatches (node_modules/@angular/core/fesm2020/core.mjs:12634:29)
                at resolveDirectives (node_modules/@angular/core/fesm2020/core.mjs:12447:31)
                at elementStartFirstCreatePass (node_modules/@angular/core/fesm2020/core.mjs:15179:27)
                at ɵɵelementStart (node_modules/@angular/core/fesm2020/core.mjs:15219:9)
                at templateFn (ng:///SignupComponent.js:104:9)
                at executeTemplate (node_modules/@angular/core/fesm2020/core.mjs:11929:9)
                at renderView (node_modules/@angular/core/fesm2020/core.mjs:11729:13)
                at renderComponent$1 (node_modules/@angular/core/fesm2020/core.mjs:12978:5)
                at renderChildComponents (node_modules/@angular/core/fesm2020/core.mjs:11588:9)
                at renderView (node_modules/@angular/core/fesm2020/core.mjs:11754:13)
                at ComponentFactory.create (node_modules/@angular/core/fesm2020/core.mjs:22313:13)
                at apply (node_modules/@angular/core/fesm2020/testing.mjs:26599:51)
                at _ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:372:26)
                at ProxyZoneSpec.onInvoke (node_modules/zone.js/fesm2015/zone-testing.js:287:39)
    

    However, ng start built without errors and the component is working just as I'd expect (no console errors or anything).

    I should add that I'm running 14.0.1 currently:

    Angular CLI: 14.0.1
    Node: 16.15.1
    Package Manager: npm 8.11.0 
    OS: darwin arm64
    
    Angular: 14.0.1
    ... animations, cdk, cli, common, compiler, compiler-cli, core
    ... forms, material, platform-browser, platform-browser-dynamic
    ... router
    
    Package                         Version
    ---------------------------------------------------------
    @angular-devkit/architect       0.1400.1
    @angular-devkit/build-angular   14.0.1
    @angular-devkit/core            14.0.1
    @angular-devkit/schematics      14.0.1
    @schematics/angular             14.0.1
    rxjs                            7.5.5
    typescript                      4.7.3
    
  13. JoostK commented on Jun 20, 2022

    @JoostK
    Member

    @t-bowersox Thanks for the info, that does indeed reveal a JIT-only bug! I have a fix in #46439.

  14. angular-automatic-lock-bot commented on Jul 22, 2022

    @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.

  15. locked and limited conversation to collaborators on Jul 22, 2022
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: corecross-cutting: standaloneneeds reproduction

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions