0

For my project, I'm trying to create dynamic component with a template in a string which contains multiple variable. So I'm using this answer: angular2 generate component from just a string

And it works well to display my data in my template. But, I can't use directive like ngIf, ngModel etc... I have the classic error: "NG0303: Can't bind to 'ngIf' since it isn't a known property of 'span' (used in the 'DynamicComponent' component template)."

I import well CommonModule and FormsModule of course.

                    const tmpCmp = Component({ template: myTemplate })(class { });
                    const tmpModule = NgModule({ declarations: [tmpCmp], imports: [CommonModule, FormsModule] })(class { });


                    const mod = this._compiler.compileModuleAndAllComponentsSync(tmpModule);
                    const factory = mod.componentFactories.find((comp) =>
                        comp.componentType === tmpCmp
                    );
                    const cmpRef = factory.create(this._injector, [], null, this._m);
                    cmpRef.instance.name = `dynamic_${j}`;
                    cmpRef.instance.data = this.data[j];
                    this.listVc.get(j).insert(cmpRef.hostView);

I'm on Angular 14 by the way.

My template looks like:

<div class="ui-grid-cell-contents text-center"> 
<input [value]="data.lastName">
<span *ngIf="data.teletrav" class="glyphicon glyphicon-ok-circle"></span>
</div>

Thanks

BaaLa
  • 31
  • 1
  • 7
  • What does your DynamicComponent look like? Do you need to import CommonModule into the hostView aswell? – Schrader Jan 12 '23 at 09:50
  • Please update your question. – Schrader Jan 12 '23 at 09:59
  • Can you provide your issue with a stackblitz? – Schrader Jan 12 '23 at 10:17
  • I made this: https://stackblitz.com/edit/angular-ivy-xwu1kg?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fhello.component.ts,src%2Fapp%2Fapp.component.ts,angular.json,src%2Fapp%2Fapp.module.ts But on stackblitz, it's working well... – BaaLa Jan 13 '23 at 09:16
  • Cant you take the new code from stackblitz? There are even different things used between your question and stackblitz – Schrader Jan 13 '23 at 13:37
  • Looks different because I use the new Angular 13/14 methods to create component/module. but the logical and result is the same – BaaLa Jan 19 '23 at 08:30
  • Okay so in my project it works well now when I diisabled AOT. But impossible when it is enabled. I tried some solutions with JIT (like this: https://www.linkedin.com/pulse/compiling-angular-templates-runtime-dima-slivin) but still the same problem – BaaLa Jan 19 '23 at 15:11
  • I am wondering. What do you mean with "new Angular 13/14 methods to create component" ? Did you mean your question or stackblitz? Because "_compiler.compileModuleAndAllComponentsSync" is marked as deprecated. https://angular.io/api/core/Compiler – Schrader Jan 20 '23 at 08:51

0 Answers0