5

I am working in a angular4 project where I had used ngx-slimscroll which has the tag with attribute as given below

<perfect-scrollbar [config]="configForScroll"></perfect-scrollbar>.

Now, here my requirement is to create <perfect-scrollbar> element dynamically using document.createElement() function which I have done successfully.But, on setting the attribute as [config] I am getting error as

Uncaught DOMException: Failed to execute 'createAttribute' on 'Document': The qualified name provided ('[config]') contains the invalid name-start character '['. So, is there any way to set this kind of attribute as shown in below code

var patt = document.createAttribute("[config]");
patt.value = "configForScroll";

Please find me a way to fix it. Thanks in advance

Krishna Prashatt
  • 631
  • 9
  • 18
Gurudath G
  • 168
  • 1
  • 2
  • 10
  • Have you tried using angular's `Renderer2`? – Pardeep Jain May 18 '18 at 12:52
  • @PardeepJain there is no use...You can't set an attribute named '[config]' using this.renderer.setAttribute(div, 'attr', 'value'); – Rohith K P May 18 '18 at 13:15
  • I dont see any point in dynamically adding this component's html string in angular app. Angular wont detect that change, and it will be considered as plain html only. Like I said please see https://angular.io/guide/dynamic-component-loader – Rohith K P May 18 '18 at 13:18
  • @Ninjaneer are you very sure about it? – Pardeep Jain May 18 '18 at 13:19
  • 1
    @PardeepJain Yes I am sure. `main.js:157843 DOMException: Failed to execute 'setAttribute' on 'Element': '[config]' is not a valid attribute name. at DefaultDomRenderer2.setAttribute ` – Rohith K P May 18 '18 at 13:20
  • Cool !!, but There must be some way to achieve this. – Pardeep Jain May 18 '18 at 13:33

1 Answers1

1

is it possible to set the attribute as [config] with value as configForScroll using setAttribute in javascript? NO

You cannot create an attribute named '[config]', with special chars '[' and ']'. Doing so will raise a INVALID_CHARACTER_ERR exception as pointed out here

INVALID_CHARACTER_ERR if the parameter contains invalid characters for XML attribute.

but you can create an attribute named 'config';

document.createAttribute("config");//valid

Please note that dynamically appending component tag won't work as expected. Angular will not detect those change. Your newly appended node will be considered as a plain Dom node, and not as angular component.

If your intention is to add a dynamic component then please look into to dynamic-component-loader and this stackoverflow answer => How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

Rohith K P
  • 3,233
  • 22
  • 28