从 Angular 设置本机 webcomponent 的回调

Set callback of native webcomponent from Angular

我有一个带有回调函数的原生 webcomponent 'myCallback'。

<script>
    class MyComponent extends HTMLElement {
        constructor() {
            super();
            this.myCallback = this.getAttribute("my-callback");
        }

        connectedCallback() {
            this.innerHTML = "MyComponent";

            const me = this;
            setTimeout(function () {
                const cb = me.myCallback;
                if (typeof cb === "string") {
                    new Function(cb).call(window);
                } else if (typeof cb === "function") {
                    cb.call(window);
                } else {
                    console.log("not a function: " + cb);
                }
            }, 1000);
        }

    }

    customElements.define("my-component", MyComponent);
</script>

我想在 Angular 中使用这个 webcomponent 并为其分配一个回调,但它似乎不起作用。这是我到目前为止尝试过的:

<my-component my-callback="angularCallback()"></my-component>
<my-component my-callback="{{angularCallback}}"></my-component>
<my-component [my-callback]="angularCallback"></my-component>
<my-component [my-callback]="angularCallback()"></my-component>
<my-component (my-callback)="angularCallback()"></my-component>

上面的第一行抛出错误"angularCallback is not a function",因为它不是在window中定义的,而是在Angular中定义的。其他行永远不会被调用,也不会抛出任何错误。

作为一个简单的测试,我尝试了以下方法并且效果很好:

<my-component my-callback="console.log('test-callback');"></my-component>

有没有办法通过模板在 Angular 中分配回调?

更新解决方案

我犯的错误是我尝试 [my-callback] 而不是 [myCallback]

所以解决方案如下:

<my-component [myCallback]="angularCallback"></my-component>

属性以字符串形式传递给自定义元素。传递函数时,在自定义元素上将其作为 属性 传递会更容易。

您可以使用 Angular 中的 [] 语法传递 属性。

<my-component [mycallback]="callbackMethod"></my-component>

回调方法是 ts 代码中的一个简单函数。

callbackMethod = () => console.log('callback method called');

然后在自定义web组件中,可以直接访问属性值。

setTimeout(function () {
    // directly access the callback property on the component
    const cb = this.mycallback;

    if (typeof cb === "string") {
        new Function(cb).call(window);
    } else if (typeof cb === "function") {
        cb.call(window);
    } else {
        console.log("not a function: " + cb);
    }
}, 1000);

我创建了一个 StackBlitz example 来说明这一点。