在 Angular 6 中扩展原生 HTML 元素

Rya*_*ieu 3 web-component custom-element angular6

我最近创建了一个在所有浏览器中运行良好的原生 Web 组件。我将此 Web 组件移动到 Angular 6 应用程序中,并且一切正常。然后我尝试扩展一个原生 HTML 元素,该元素再次完美运行,除非我将它带入我的 Angular 6 应用程序。

使用 Mozilla 的示例,我将尝试说明我的问题。使用以下尝试扩展本机“p”元素:

// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    super();

    // count words in element's parent element
    var wcParent = this.parentNode;

    function countWords(node){
      var text = node.innerText || node.textContent
      return text.split(/\s+/g).length;
    }

    var count = 'Words: ' + countWords(wcParent);

    // Create a shadow root
    var shadow = this.attachShadow({mode: 'open'});

    // Create text node and add word count to it
    var text = document.createElement('span');
    text.textContent = count;

    // Append it to the shadow root
    shadow.appendChild(text);


    // Update count when element content changes
    setInterval(function() {
      var count = 'Words: ' + countWords(wcParent);
      text.textContent = count;
    }, 200)

  }
}

// Define the new element
customElements.define('word-count', WordCount, { extends: 'p' });
Run Code Online (Sandbox Code Playgroud)
<p is="word-count">This is some text</p>
Run Code Online (Sandbox Code Playgroud)

通过使用相同的代码并将其放入 Angular 6 应用程序,该组件永远不会运行。我将控制台日志语句放在构造函数和 connectedCallback 方法中,它们从不触发。如果我删除 {extends: 'p'} 对象并更改 extends HTMLParagraphElement 并使其成为一个扩展 HTMLElement 成为一个自治的自定义元素,那么一切都会很好地工作。我做错了什么还是 Angular 6 不支持自定义的内置元素扩展?

con*_*exo 5

我认为原因是 Angular 在解析组件模板时创建那些自定义的内置元素的方式 - 它可能不知道如何正确地做到这一点。奇怪的是它认为is一个常规属性可以创建元素添加(它不是)。

is不幸的是,首先创建元素然后添加-attribute不会升级元素。

见下面的例子:div#d有一个自定义的非工作示例input

customElements.define('my-input', class extends HTMLInputElement {
  connectedCallback() {
    this.value = this.parentNode.id
    this.parentNode.classList.add('connected')
  }
}, {
  extends: 'input'
})

document.addEventListener('DOMContentLoaded', () => {
  b.innerHTML = `<input type="text" is="my-input">`

  let el = document.createElement('input', {
    is: 'my-input'
  })
  el.type = 'text'
  c.appendChild(el)

  // will not work:
  let el2 = document.createElement('input')
  el2.setAttribute('is', 'my-input')
  el2.type = 'text'
  d.appendChild(el2)
})
Run Code Online (Sandbox Code Playgroud)
div {
  border: 3px dotted #999;
  padding: 10px;
}

div::before {
  content: "#"attr(id)" ";
}

.connected {
  background-color: lime;
}
Run Code Online (Sandbox Code Playgroud)
<div id="a"><input type="text" is="my-input"></div>
<div id="b"></div>
<div id="c"></div>
<div id="d"></div>
Run Code Online (Sandbox Code Playgroud)

所以为了让它与 Angular 一起工作,挂钩到你的 Angular 组件的生命周期(例如onInit()回调)并选择一种工作方式在那里创建你的元素。