首页 > 解决方案 > 如何从 Angular 应用程序向 javascript Web 组件提供输入

问题描述

我已经使用 HTMLElement 类创建了 JavaScript WebComponent。并使用 npx webpack 构建它。现在尝试在 Angular 7 项目中使用该组件,但是当我尝试通过创建变量从 angular 提供输入时,它不起作用,但是当我直接输入字符串时它起作用。下面是我的网络组件。基本上是一个带有显示/隐藏输入的加载器。

if (typeof require !== 'undefined') {
    require('../css/styles.css');
}

class Loader extends HTMLElement {
    constructor() {
        super();
        this.initialized = false
    }

    static get observedAttributes() {
        return ['data-input'];
    }


    attributeChangedCallback(name, oldValue, newValue) {
        console.log(name, newValue);

        if (name == 'data-input') {
            if (newValue == 'show' && this.shadowRoot) {
                this.shadowRoot.getElementById('my-component').className = 'show';
            } else if (this.shadowRoot) {
                this.shadowRoot.getElementById('my-component').className = 'hide';
            }
        }
        if (!this.initialized) {
            this.buildElement();
            this.initialized = true
        }
    }

    buildElement() {
        const shadowRoot = this.attachShadow({mode: 'open'});
        let style = document.createElement('style');
        let cssFile = ''
        if (typeof require !== 'undefined') {
            cssFile = require('../css/styles.css');
        }
        style.textContent = cssFile; 
        shadowRoot.appendChild(style);
        shadowRoot.appendChild(this.createElement());      
    }

    createElement() {
        const container = document.createElement("DIV");
        container.id = "my-component";
        container.className = "hide";
        const loader = document.createElement("DIV");
        loader.className = "loader";
        container.appendChild(loader);
        const locker = document.createElement("DIV");
        locker.className = "locker";
        container.appendChild(locker);
        return container;
    }
}

window.customElements.define('my-component', My);

这行得通。

<my-component data-input="show"></my-component>

但这不起作用。

<my-component data-input="{{showHideInput}}"></my-component>

标签: javascripthtmlangularweb-component

解决方案


你试过了吗:

<my-component data-input={{showHideInput}}></my-component>?


推荐阅读