问题描述
我正在尝试构建一个将由Angular应用程序使用的自定义元素.自定义元素将使用道具并可能对其进行操纵.
I'm trying to build a custom element that will be consumed by an Angular app. The custom element will take a prop and potentially manipulate it.
我的理解是,我可以使用盒子里的香蕉"来处理这种绑定,也可以将<custom-element [(foo)]="bar">
转换为<custom-element [foo]="bar" (fooChange)="bar = newBar">
等.
My understanding was that I could use the "banana in a box" to handle this binding, aka <custom-element [(foo)]="bar">
gets converted to <custom-element [foo]="bar" (fooChange)="bar = newBar">
, or the like.
我的Angular模板:
My Angular template:
<an-el [(clicked)]="isClicked"></an-el>
<p>Did you click a button? {{ isClicked }}</p>
我的自定义元素调度一个事件:
My custom element dispatches an event:
this.dispatchEvent(new CustomEvent('clickedChange', { bubbles: true, detail: true }));
this.dispatchEvent(new CustomEvent('clickedChange', { bubbles: true, detail: true }));
但是它似乎将整个CustomEvent绑定到isClicked
:
But it appears to bind the entire CustomEvent to isClicked
:
Did you click a button? [object CustomEvent]
我在做什么错了?
这是我的应用程序(在Chrome中运行): https://stackblitz.com/edit/angular-nlguf4
Here's my app (run in Chrome): https://stackblitz.com/edit/angular-nlguf4
推荐答案
我将isClicked
声明替换为:
private _isClicked = false;
public get isClicked() {
return this._isClicked;
}
public set isClicked(val: CustomEvent | boolean) {
this._isClicked = typeof val === "boolean" ? val : val["detail"];
}
这篇关于如何实现Angular的“盒子里的香蕉"与自定义元素进行双向绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!