0

The child nodes which Iam appending are not properly positioned inside the ng-content area of the custom element I created using Angular element.

I tried to reporduce my issue in this Stackblitz

Current solution

It will work if I add the child nodes to the created custom element instance before adding to dom .

Expected Solution

Is there any way I can easily add a childnode to my custom angular element using javascript(appendChild) without rerendering the whole component again.

Thanks.

Sachin
  • 2,627
  • 1
  • 19
  • 35

2 Answers2

1

You could use getElementsByClassName:

onAddChild2(e: string) {
  let div = document.createElement("div");
  div.innerHTML = e;

  const eHost = document.getElementsByClassName('container')[0];
  eHost.appendChild(div);
}

Check the Stackblitz I forked from you code: https://stackblitz.com/edit/angular-elements-exp-v3r4b3

Kari F.
  • 1,214
  • 10
  • 16
  • I know this but wanted to check whether we have a solution native to angular , Thanks. – Sachin Dec 16 '19 at 07:21
  • Well, in fact you didn't ask for a native solution. You posted a stackblitz that wasn't working and asked this: "Is there any way I can easily add a childnode to my custom angular element using javascript(appendChild) without rerendering the whole component again." – Kari F. Dec 16 '19 at 14:14
1

This is not the Angular way. You should not be manipulating the DOM directly like this. You should be binding an array to your template.

children = ['New Child'];

onAddChild() {
  this.children.push('New child');
}

and in the template

<div *ngFor="let child of children">{{child}}</div>
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • Yeah , but not want to use the *ngFor as it will rerender the entire list. – Sachin Dec 16 '19 at 07:23
  • No it wont, Angular change detection maps what has changed and only renders what has been updated. If you append a value to the end of the array it is only going to add the new node, it will not rerender the whole array. You should read up on how Angular change detection works. This is the Angular native solution that you are looking for. – Adrian Brand Dec 16 '19 at 09:53