Skip to content

Dynamic standalone component can not resolve FormsModule (probably others from @angular/*) #48034

Closed

Description

@ghost81

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

core

Is this a regression?

No

Description

I have a standalone component defined like this:

import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

export const componentMetadata : Component = {
	jit: true,
	standalone: true,
	selector: '<dynamic-component>',
	imports: [
		FormsModule, CommonModule
	],
};
export class DynamicComponent {
	
	public constructor() {}
....
}

Then I have component that should create dynamically, as a child, this component, with template that is coming from DB.
Sample code:

import ....

@Component({
	standalone: true,
	selector: '<container-component>',
	template: '<ng-container #content></ng-container>',
	providers: [ {
		provide: NG_VALUE_ACCESSOR,
		useExisting: forwardRef(() => ContainerComponent),
		multi: true
	}],
})

export class ContainerComponent implements OnInit, OnDestroy, ControlValueAccessor {
.....
    @ViewChild('content', { read: ViewContainerRef, static: true })
    contentContainer: ViewContainerRef;
.....
    private async createContent() {
	this.cleanComponentRef();
	const component = await this.setupContentComponent(this.content); // we have content when we reach this method
	this.componentRef = this.contentContainer.createComponent(component, {
		injector: this.contentContainer.injector,
	});
    }

    private async setupContentComponent(content: string = '') {
	const defs = await import('./dynamic.component');
	const currentMeta = { ...defs.componentMetadata };
	currentMeta.template = content;

	return Component(currentMeta)(defs.DynamicComponent);
    }

    private cleanComponentRef() {
	if (this.componentRef) {
	    this.componentRef.destroy();
	    delete this.componentRef;
        }
    }
}

The content is angular template with directives like ngModel.
The problem is that i get a lot of Can't bind to 'ngModel' since it isn't a known property of...., but Forms module is imported in the dynamic component and should be compiled properly (IMO)

During investigation I reached a function in core.mjs function getStandaloneDefFunctions(type, imports) {
when checking for exported directives in this code:

if (!!getNgModuleDef(dep)) {
  const scope = transitiveScopesFor(dep);
  for (const dir of scope.exported.directives) {

dep (FormsModule) doesn't have any exported members

scope {
"schemas": null,
"compilation": {
"directives": {},
"pipes": {}
},
"exported": {
"directives": {},
"pipes": {}
}
}

Please provide a link to a minimal reproduction of the bug

StackBlitz

Please provide the exception or error you saw

NG0303: Can't bind to 'ngModel' since it isn't a known property of

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

Angular CLI: 14.2.9
Node: 19.0.1 (Unsupported)
Package Manager: npm 8.19.2 
OS: linux x64

Angular: 14.2.10
... animations, common, compiler, compiler-cli, core, forms
... localize, platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1402.9
@angular-devkit/build-angular   14.2.9
@angular-devkit/core            14.2.9
@angular-devkit/schematics      14.2.9
@angular/cdk                    14.2.7
@angular/cli                    14.2.9
@schematics/angular             14.2.9
rxjs                            7.5.7
typescript                      4.7.4

Anything else?

This is happening when aot: true in angular.json
When aot: false, then all is working but then template translations (all tags in .html files having i18n attribute) are not expanded, but all @localize'text' messages are. Probably this is for another issue / discussion

Activity

  1. JoostK commented on Nov 11, 2022

    @JoostK
    Member

    Are you compiling your application using optimization: true? If yes, then this doesn't work as the JIT compiler requires data that is removed in optimized production builds.

    If not, please provide a runnable reproduction, ideally using StackBlitz.

  2. added
    needs reproduction
    on Nov 11, 2022
  3. added
    area: core
    on Nov 11, 2022
  4. added this to the Backlog milestone on Nov 11, 2022
  5. ghost81 commented on Nov 11, 2022

    @ghost81
    Author
    "aot": true,
    "buildOptimizer": false,
    "optimization": false,

    let me try with StackBlitz

  6. ghost81 commented on Nov 11, 2022

    @ghost81
    Author

    It's interesting that in StackBlitz it doesn't show any errors, but it is not working on second pass.
    On my local environment it fails on the first pass with NG0303: Can't bind to 'ngModel' since it isn't a known property of....
    StackBlitz

  7. JeanMeche commented on Nov 12, 2022

    @JeanMeche
    Member

    I did a test on my side.

    It seems neither pipes nor module imports work with dynamic components & standalone. (JIT works fine if you remove the pipe)

  8. JoostK commented on Nov 13, 2022

    @JoostK
    Member

    I did a test on my side.

    It seems neither pipes nor module imports work with dynamic components & standalone. (JIT works fine if you remove the pipe)

    Is this comment supposed to be for #47996?

  9. JeanMeche commented on Nov 14, 2022

    @JeanMeche
    Member

    No, this one ! You can see it in this file !

  10. JoostK commented on Nov 14, 2022

    @JoostK
    Member

    In that case the repo's README is pointing at the wrong issue.

  11. JeanMeche commented on Nov 14, 2022

    @JeanMeche
    Member

    Good point, I used the same branch for both issues. I updated the read me.

  12. ghost81 commented on Nov 14, 2022

    @ghost81
    Author

    Can someone remove needs reproduction label as I already provided one?

  13. alxhub commented on Nov 15, 2022

    @alxhub
    Member

    @ghost81 can you provide a more minimal reproduction? There's a number of extra components in that Stackblitz, and no clear instructions or description of what's expected to work, what errors are occurring, etc. I see a half broken UI, a StaticComponent that appears to be doing some kind of dynamic recursion, and no clear errors in the console that would suggest something isn't working correctly.

  14. ghost81 commented on Nov 15, 2022

    @ghost81
    Author

    I updated stackblitz, and i can't do it more minimal than the new state.
    And is I already said, it is working on stackblitz, but if you download the project and run it, you will see the error:
    NG0303: Can't bind to 'ngModel' since it isn't a known property of 'static1' (used in the 'DynamicContentComponent' component template).

  15. alxhub commented on Nov 15, 2022

    @alxhub
    Member

    Thanks, I was able to reproduce the behavior you describe. I think this is working as intended, although we don't have great documentation on the nuances here.

    Angular CLI has two compilation modes: AOT or JIT. What it doesn't support are "hybrid" applications where some components are AOT compiled and others use the JIT compiler. That's because when AOT mode is enabled, the CLI configures its build to strip away extra runtime information which is only required to support JIT compilation.

    So setting aot: false in angular.json is the right way to build such applications - putting the CLI into JIT mode will ensure all of the metadata needed to dynamically compile components at runtime is retained.

  16. ghost81 commented on Nov 15, 2022

    @ghost81
    Author

    Yeah, I read about this some time ago in stackoverflow or in an issue posted here.
    And now another problem arise, as we also have translations in templates, which requires AOT: true.
    I'm searching for decision that can use JIT compilation with i18n in templates OR what you call "hybrid", so we can use translations in templates.
    Please, advice for a good way to combine both.
    Variants like "put your strings in .ts file" seams not acceptable

  17. ghost81 commented on Nov 15, 2022

    @ghost81
    Author

    BTW, it is still of high interest how the hybrid model is working on stackblitz

  18. ghost81 commented on Nov 18, 2022

    @ghost81
    Author

    Same as:
    44660
    22570

    But in JIT compilation we can't have component templates translated

  19. ghost81 commented on Nov 22, 2022

    @ghost81
    Author

    I finally succeeded to get hybrid model working.
    For our personal case we need not so much - just NgModel, NgIf and NgFor
    I created a module with following code (we are at angular 15 where NgIf and NgFor are standalone, may be for older versions it should be tuned)

    import { NgFor, NgIf } from "@angular/common";
    import { NgModule } from "@angular/core";
    import { NgModel } from "@angular/forms";
    
    @NgModule({
    	jit: true,
    	imports: [ NgIf, NgFor ],
    	declarations: [
    		NgModel
    	],
    	exports: [
    		NgModel, NgIf, NgFor
    	]
    })
    export class JitModule {
    }

    Our project now is compiled with aot: true, dynamic components have jit: true and all they import the JitModule
    I don't know how long this will work and if it will change in the future versions, but it is a live-saver for the time of writing

  20. angular-automatic-lock-bot commented on Dec 23, 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.

  21. locked and limited conversation to collaborators on Dec 23, 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: coreneeds reproduction

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions