M
M
Maxim Fedorov2021-04-18 19:41:01
Angular
Maxim Fedorov, 2021-04-18 19:41:01

Why is not a known element when creating a component dynamically?

Here is the template:

<ng-container *ngTemplateOutlet="staticForm"></ng-container>

<template #formDynamic></template>

<ng-template #staticForm>
  <form class="container" [formGroup]="testForm">
    <tui-text-area formControlName="value">Введите текст</tui-text-area>
  </form>
</ng-template>


Here is the code from dynamic template creation:
compileFromRaw(template: string, data: any): ViewRef {

    const styles: string[] = [];
    function TmpCmpConstructor() {
      // @ts-ignore
      this.data = data;
    }

    // @ts-ignore
    const templateComponent = Component({template, styles})(new TmpCmpConstructor().constructor);

    const tmpModule = NgModule({
      imports: [],
      declarations: [templateComponent],
    })(class {
    });

    const factories = this.compiler.compileModuleAndAllComponentsSync(tmpModule)
    const f = factories.componentFactories[0];

    this.componentRef = f.create(this.injector, [], null, this.moduleRef);
    this.componentRef.instance.name = 'my-dynamic-component';

    return this.componentRef.hostView;
  }


This is how I create a new component and insert it into a dynamic template:
this.container.insert(this.compiler.compileFromRaw(
        '<form class="container" [formGroup]="testForm">\n' +
        '    <tui-text-area formControlName="value">{{data}}</tui-text-area>\n' +
        '  </form>',
        'Введите текст 2',
      ));


RESULT: html was generated correctly and data was substituted, but swears that the NG0304: 'tui-text-area' is not a known elementstatic version was displayed correctly!

607c61c6ee47d165262002.png

I’ve been messing with this for the second day, I can’t figure it out, I’ve only been working with the frontend for a week

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sun_Day, 2021-04-18
@Maksclub

Some code is a bit ugly. Especially if it will be supported after you. It is better to copy one to one from the docks, there are examples .
I don't know what is statically displayed there, but the error indicates that tui-text-area is not declared. tui-text-area must be added to the declarations of the module, or the module in which this component is connected must be imported.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question