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

Is it possible to initiate the onchange event in Angular programmatically using Typescript?

Despite changing the value of an input tag after returning a value from a dialog box (MatDialogRef), the associated change event fails to trigger. Attempts to use dispatchEvent have been made, but creating the event for triggering is not desired as per fo ...

Create a nested array of subcategories within an array object

Currently, I am working on integrating Django Rest and Angular. The JSON array received from the server includes category and subcategory values. My goal is to organize the data such that each category has its related subcategories stored as an array withi ...

Pause for a moment before displaying the VueJS loading screen

When using VueJS, I have implemented a loader to be displayed on each route like this: router.beforeEach((to, from, next) => { store.commit('loading', true); next(); }) However, it seems unnecessary to show the loader for a request that ...

Obtaining Relative Values within Every Iteration using jQuery

I'm currently facing an issue with retrieving relative values within a .each() loop using jQuery. I have a set of table rows that contain a text input and a radio button each. My objective is to iterate through each row and save the value of the text ...

What is the best way to create a function that automatically resumes audio playback 3 seconds after the pause button is clicked?

I am looking to develop a basic webpage with an autoplay audio feature. The page would include a "pause" and "play" button. I aim to implement a function where clicking the "pause" button would stop the audio, but after 3 seconds, it would automatically re ...

When PHP is connected to the database, Ajax remains inactive and does not perform any tasks

I am currently working on setting up a simple connection between JavaScript and my database using ajax and PHP. The goal is for JavaScript to receive a name from an HTML form, make changes to it, send it to PHP to check if the name already exists in the da ...

What causes my ready function to consistently execute upon controller or directive reinitialization?

Every time my controller or directive reinisilize, the angular.element(document).ready(function(){...}); function is executed. Why does this happen? In my scenario, I have two controllers and one directive. I update a value in the parent controller which ...

Improving mongo information using angularjs

Have an Angular and MongoDB application. This is a part of my API where I have POST and PUT requests. The POST request works fine, but when I send a PUT request, I get an error "Cannot set property 'typelocal' of undefined". However, the PUT requ ...

TypeScript's robustly-typed rest parameters

Is there a way to properly define dynamic strongly typed rest parameters using TypeScript 3.2? Let's consider the following scenario: function execute<T, Params extends ICommandParametersMapping, Command extends keyof Params, Args extends Params[C ...

Utilizing ng-class for dynamic routing and controlling

I am currently in the process of developing a dynamic framework using AngularJS. My plan involves allowing users to add new templateUrl and controller from a JSON file, like the one shown in templates.json: { "pages" : [ { "name" : "home" ...

"Retrieve a specific object from a JSON file using NextJS based on its ID

NextJs is the framework I am currently utilizing for my project. Is there a way to render a specific project based on its unique ID? { “projects”: [ { "id": 1, "picture": "portf.jpg" }, { ...

The like button animation works perfectly for individual posts, but for multiple posts, only the like button on the first post

Having an issue with the like button code on a single news feed. The button works for the first post, but when clicking on other posts, it only affects the first post button. I am using post UI and looping the UI based on the total post count without Javas ...

Detecting single letters in a sentence and changing their appearance using CSS

Looking to make a subtle change to text? I need to swap out single letters in a passage (I have a cat that ate a fish). Any ideas on how to do this? The goal is to input a block of text into a textbox, then display it in a div. I've had difficulty fi ...

Filter a two-dimensional array based on the presence of a string value found in the second array

My logic for this assignment is not very good, as I need to filter a 2D array based on the values of another array. Let me provide an example of the 2-Dimensional Array: const roles = [ ['roles', 'admin', 'write'], ['ro ...

Accessing my data on my personal server through firestore entails an extra step in the request process

If I were to set up Cloud Firestore on my personal server, wouldn't that create a "two-way trip" for accessing my data? What I find concerning is the fact that the client-side has to send a request to my server first, and then my server must reach ou ...

How can we initiate the AJAX request right away while also making sure the page is fully loaded before adding

One trick I've discovered is that by submitting an AJAX request in the <head> section of my webpage, I can avoid a minor flicker on page load when loading content via AJAX. Of course, this method still needs some refining to handle longer AJAX r ...

"Quotes are essential in Javastript syntax for specifying string values

I need to implement a JavaScript syntax to generate unique URLs for each image. The Robohash website provides random robot images based on different URL endings. I tried the code below, but it seems like ${props.id} is being interpreted as part of the UR ...

Sending a string parameter from an AJAX function to a Spring controller

I'm currently developing a standalone application and facing an issue with passing a string, which is generated from the change event, to the spring controller using the provided code snippet. Here is the HTML CODE snippet: <!DOCTYPE HTML> < ...

What is the best way to display an HTML page in the bottom right corner instead of within a div?

I am trying to display the content of an HTML page in the bottom right corner of another page using my JavaScript script. However, I do not want to insert a div into the page and then load the content inside it. Instead, I am looking for an alternative way ...

Create a new promise within a factory function

I am facing an issue in my factory where I want to return a promise inside a function, but every time I try, my controller throws an error like: Provider 'personFactory' must return a value from $get factory method. This is how my factory looks ...