When should I apply the pattern in the constructor or connectedCallback

When should I apply a pattern in constructor

or connectedCallback

? When I do this in the callback, sometimes attributeChangedCallback

before is called and I cannot request items.

export class TestElement extends HTMLElement {
  constructor() {
    super();
    //here ?
  }

  connectedCallback() {
    //here ?
  }
}

      

I would like to know where and why this is better.

Here is a debugged template applies the code

let t = document.createElement('template');
t.innerHTML = require('template.html');
this.appendChild(t.content.cloneNode(true));

      

+3


source to share


1 answer


Unless you are using Shadow DOM, you shouldn't be embedding the template in the callback constructor()

.

Therefore, you should only add it to connectedCallback()

.



Either way, attributeChangedCallback()

it can be called before or after the above callbacks depending on how your custom element is being used. Therefore, you should always do a test before trying to query some internal elements.

+2


source







All Articles