1

I am creating an Angular application in which I don't have to use the HTML file means I cannot edit the HTML file (for purpose) manually. In the below Pseudo code, I am using the setAttribute() method to set the id attribute to the div I click on -

  constructor(
    private renderer: Renderer2
  ) { 
    this.renderer.listen(document.body, 'click', (event) => {
      this.elementHandler(event.srcElement);
    });
  }

  elementHandler(element: any) {
   if (!element?.id) {
     element.setAttribute('id', 'someId');
   }
 }

Now, all I want is to append an Angular component inside that specific div with the Id that I had set using elementHandler Method as shown in the above code.

Note - The Angular component I want to append is imported from the library - @kolkov/angular-editor( https://www.npmjs.com/package/@kolkov/angular-editor ) and the component I want to append to the HTML file -

<angular-editor [(ngModel)]="htmlContent" [config]="config"></angular-editor>

How I can achieve it ?

Would be very grateful for your help.

ABC
  • 31
  • 6
  • Why not just use `*ngIf` ? – AdityaParab May 26 '23 at 13:54
  • Because I cannot edit the HTML file manually. Understand this way, it's something like I got an HTML template from someone that is read-only that I cannot edit it manually and I have to edit it using a Typescript file in angular ( that is the mandatory requirement ), so we are not allowing to edit the HTML file manually. Anyway, we do not want to play with HTML file manually. – ABC May 26 '23 at 14:05
  • Here are some references for dynamically adding an angular component at runtime: [SO answer](https://stackoverflow.com/a/44942210/4192097), [official docs](https://angular.io/guide/dynamic-component-loader). – MikeJ May 28 '23 at 04:01
  • Why I cannot pass the angular component as innerHTML, is there any way I can do it ? like - document.getElementById("someId").innerHTML = ' ?? – ABC May 29 '23 at 10:44
  • @MikeJ, all you provided need to add a template reference variable something like this - in HTML file and I have no way to add anything like that to HTML, I repeat again I cannot edit HTML manually and that is the actual challenge.And this the requirement of the application that we are not allowing anything to add in HTML manually we can just manipulate it using ts. – ABC May 29 '23 at 10:49
  • I won't post it as an answer because it doesn't answer what you're asking specifically, but [here's a StackBlitz](https://stackblitz.com/edit/stackblitz-starters-be5vdf?file=src%2Fmain.ts) showing how you could create a Directive that targets all div elements and listens for a custom event on its host. You could then dispatch that custom event on your target el, triggering the directive to append a component to its host. Maybe that could point you in the direction of a solution. Not sure it's possible to append an angular component tag as if it's a native el and expect angular to integrate it. – MikeJ May 30 '23 at 03:23

0 Answers0