Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this:

//code

 /**
 * @param template is the HTML template
 * @param container is  @ViewChild('dynamicFront', { read: ViewContainerRef }) _containerFront: ViewContainerRef;
 */
private addComponent(template, container) {
    @Component({
      template: template
    })
    class DynamicComponent {
    constructor(public _parent: TemplateEditorComponent) {
      this._parent.templateForm.controls['field_heading'].valueChanges.subscribe(value => {
        console.log(value);
      })
    }

    }
    @NgModule({
        imports: [
            ReactiveFormsModule,
            BrowserModule,
            EditorModule
        ],
        declarations: [DynamicComponent, EditableDivDirective, InlineEditorDirective]
    })
    class DynamicComponentModule { }

    const mod = this.compiler.compileModuleAndAllComponentsSync(DynamicComponentModule);
    const factory = mod.componentFactories.find((comp) =>
      comp.componentType === DynamicComponent
    );
    const component = container.createComponent(factory);
}

and in the HTML component I am displaying the template like this:

<ng-template #dynamicFront></ng-template>

I am encountering some build errors such as the template not being a string, etc. My goal is to display raw HTML content retrieved from the database and allow users to edit text within this raw HTML template using TinyMCE for editing purposes.

Answer №1

For components with dynamic templates, it is recommended to utilize <ng-template> or embedded components with inputs and outputs.

If you need clarification on the ng-template directive, check out this informative tutorial.


Update:

Your current code may be overly complex for a basic scenario. If your goal is simply to display different templates based on controller data, consider enhancing your existing template to increase its dynamism.

<ng-container *ngIf="template == 1" 
              [ngTemplateOutlet]="template1" 
              [ngTemplateOutletContext]="{value: value}">
</ng-container>

<ng-container *ngIf="template == 2" 
              [ngTemplateOutlet]="template2" 
              [ngTemplateOutletContext]="{value: value}">
</ng-container>

...

<ng-template #template1 let-value="value">
    <div class="template-1-container">
        {{value}}
    </div>
</ng-template>

<ng-template #template2 let-value="value">
    <div class="template-2-container">
        {{value}}
    </div>
</ng-template>

To incorporate logic within the templates, you can easily switch to component-based templates like so:

<app-template-one *ngIf="template == 1"
                  [value]="value">
</app-template-one>

<app-template-two *ngIf="template == 1"
                  [value]="value">
</app-template-two>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Upon pressing the submit button in the router.post function, a null value appears

In my form, I am attempting to redirect the page to the home URL after clicking the submit button. However, using res.redirect('/home') is not achieving the desired result. I have also tried using console.log("testing");, but that is not working ...

Utilize the ng-controller directive with unique aliases across various sections of HTML code

I'm facing an issue with my ng-controllers when multiple controllers are used on the same page. For instance, I have one controller in the page header, another in a different section of the same page, and one in the content of the page. However, all o ...

Encountering NaN in the DOM while attempting to interpolate values from an array using ngFor

I am working with Angular 2 and TypeScript, but I am encountering NaN in the option tag. In my app.component.ts file: export class AppComponent { rooms = { type: [ 'Study room', 'Hall', 'Sports hall', ...

Only one bootstrap collapse is visible at a time

Currently, I am using Bootstrap's collapse feature that displays content when clicking on a specific button. However, the issue I am facing is that multiple collapses can be open at the same time. I want to ensure that only one collapse is visible whi ...

The hyperlink element is failing to load in a particular frame

I've been attempting to load the URL of an anchor tag in a specific frame. I've tried various methods through online searches, but have not found a satisfactory solution. Can someone please assist me with how to load the href URL in a particular ...

If the next element in the sequence happens to be the final element, then conceal a separate

Continue pressing the downward button consistently on until you reach the bottom. The down arrow should disappear slightly before reaching the end. Is there a way to achieve this using the code provided below? I'm new at this, but I believe I need t ...

Why does the error message "$(…).functionName() is not a function" occur and what steps can be taken to prevent it from

I have encountered a console error message: $(...).functionName() is not a function Here is my function call: $("button").functionName(); This is the actual function: $.fn.functionName = function() { //Do Something }(jQuery); What ca ...

What is the best way to implement an Angular Guard that utilizes an API service for validation and redirects in case of failure?

Hello there! I am currently working on an Angular 7 application that deals with time cards. One of the main features I have implemented is a CanActivate Guard for controlling access to certain components. The CanActivate code utilizes Observables to decid ...

When iterating over objects in JavaScript, the loop may return undefined, while using Lodash's map

After encountering an issue with a JavaScript loop where the value was returning as null upon completion, I decided to try using lodash for the same purpose and it successfully returned the result. This is what I attempted: JavaScript: const jsRows = Ob ...

What is the best way to create a TypeScript function similar to a 'map' in React?

I recently started learning TS and am having trouble typing this arrow function: const mapLikeGet = (obj, key) => { if (Object.prototype.hasOwnProperty.call(obj, key)) return obj[key] } ...

What is the correct way to format responses written within response.write() in NodeJS?

Just starting out with NodeJS and express and following a tutorial on displaying two headings in the browser. Came across an issue where using res.send() twice wasn't working, so my instructor introduced me to the write method. Interestingly, when she ...

Add a fresh item to a list using jQuery

Attempting to add a new list item using jQuery. In this scenario, the process works well, but when attempting to retrieve the value of an input field using .val(), no list item is created. http://www.example.com Code snippet: $(document).ready(functi ...

Is there an image overlapping another image?

Currently, I am working on developing a website for a Food Cart project in my class. One of the key features I want to incorporate is the ability for users to click on an image of a plate and have a different image representing the food appear on top of it ...

Files for the Express API and Sequelize are nowhere to be found

After collaborating with a Freelance developer for more than 10 months on a project, the developer suddenly disappeared without warning. Although he sent me a file containing the work he had completed, I realized that the backend API was missing. Project ...

What is the best way to incorporate a sliding effect into my cookie form?

I created a cookie consent form for my website and I'm looking to include a sliding effect when it first appears and when it disappears after the button is clicked. How can I implement this sliding effect into the form? Here's the HTML, CSS, and ...

Chaining inheritance through Object.create

Recently, I decided to experiment with Object.create() instead of using new. How can I achieve multiple inheritance in JavaScript, for example classA -> classA's parent -> classA's parent's parent, and so on? For instance: var test = Objec ...

Changing text array to field identifiers with JavaScript

Is there an elegant way in ECMAScript 6 to transform a string array generated from a map function into field names within a dynamically created object? For instance, if I receive the following output from my map function: ["checkbox1Value", "checkbox4Val ...

Receiving a form submission via POST method from an external source without redirection

Situation: A user visits site A and submits a form with a hidden input field containing base64 encoded data. The action leads to site B, which is an Angular 2 application. The structure of the form is as follows: <form id="partner" method="POST" actio ...

Problem with Angular: ng-show not constantly re-evaluating expression

Utilizing a variable named activeScope to manage the state and toggle between two forms. This variable updates its value when a tab is clicked, triggering changeScope. While the change in active states for the tab buttons registers correctly, the divs for ...

Add an input element to a form fieldset by employing vue

In my form, I have a staged approach with 3 fieldsets that only appear when the "Next" button is clicked. Now, in the third fieldset, I need to add input elements based on keys extracted from an external json object. Data: data: () => ({ c ...