我正在构建一些
它可以正常工作,并包含所有自然的Angular好处。但是,我遇到的问题是,如何从普通的
这可以在
WebComponent
,我将在不同的库/框架中使用它们,但大多数是使用原生的JavaScript
。我正在考虑使用Angular Elements 来实现这个目标,并根据几个文档构建了一个示例。它可以正常工作,并包含所有自然的Angular好处。但是,我遇到的问题是,如何从普通的
JavaScript
中读取Web组件中的数据,类似于var result = myComponent.value
。
- 请注意,我要读取的数据不是原始数据或单个值。它类似于从复杂的
WebComponent
中获取许多详细信息的对象。 - 我希望像
readonly property
那样做。 - 标准的
Angular
组件文档总是使用@Output()
和EventEmitter
来实现此目的。但由于我将在Angular
之外的WebComponent
中使用该组件,因此我不能(也不想)使用这种方法。另外,我不想在每次更改值时都进行通知,而只是在需要时读取该值。
class MyComponent extends HTMLElement {
constructor() {
super();
this.name = 'Guest';
this.count = 0;
}
// more code...
// THIS result PROPERTY IS USED TO READ DATA FROM THE WEB COMPONENT
get result() {
return { name: this.name, count: this.count }; // <<== to read data
}
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
styles....
</style>
<h1>MyComponent</h1>
More HTML...
`;
}
}
customElements.define('my-component', MyComponent);
// Then I can use <my-component></my-component> in my application HTML
// And in the JavaScript code, I can read data from my-component as
const result = document.querySelector('my-component').result;
// which would be something like { name: 'Guest', count: 0 }
这可以在
AngularElements
中实现吗?
Object.defineProperty
吗? - Danny '365CSI' EngelmanObject.defineProperty()
在这种情况下如何有所帮助吗? - Arghya C