0

I am trying to attach the element to parent DOM onClick. how to call the component dynamically? If I add simple " hello world , it works as expected. but I want to call the "myCustomTag" component.

Note: If I add "myCustomTag tag" directly in the template, it works. It is attaching the "myCustomTag" template as expected.

     @Component({
      selector: 'myTag',
      template: `<div (click) = "onAttachClick()"> clickToAddELement </div>`
    })
    export class xxx {
     getNewElement() {
         return '<myCustomTag [name]="someText"></myCustomTag>'
        }
        //on click, I need to add the element
        onAttachClick() {
       this.parentElement.insertAdjacentHTML('beforeend',this.getNewElement());
        }
}
Dns
  • 11
  • 1

1 Answers1

0

You can set up a local variable in

<div #myAttach (click) = "onAttachClick()"> clickToAddELement </div>

And use

export class xxx {
   @ViewChild('myAttach') myAttach;
   ....
}

then

this.myAttach.nativeElement.insertAdjacentHTML('beforeend',this.getNewElement());

Reading this might help you: What's the proper way of accessing native element in angular2 (2 diff ways) docs are scarce

Community
  • 1
  • 1
David
  • 312
  • 3
  • 10
  • 1
    Hi David, thanks for the reply. Attaching an element is fine.. But I was unable to call "mycustamtag" component .. It is attaching empty html element to the parent. Some how I want to call "mycomponent" with the html – Dns Feb 07 '17 at 15:17
  • @Dns Ah I see. Could you show me how you implement ? – David Feb 08 '17 at 06:25