Stencil object properties are not set, when they provided through the HTML string

Deadly 提交于 2021-02-08 06:52:37

问题


According to documentation, Stencil component's property myProperty

  @Prop({attribute: "my-prop"})
  public myProperty?: object = {};

should be set by using this HTML code:

  <my-component my-prop="{hello: 'world'}" ></my-component>

But, instead, it's set to default value (empty object). Boolean and string values work fine.

Is it a bug, or I've overlooked something?


回答1:


Stencil does not automatically parse object properties. You have two options:

  1. Set the property using JavaScript
  2. Set it as a HTML attribute (as valid JSON) and manually parse it to an object which you can store in a @State property.

One change to the manual parsing I always include is checking if it's actually an object in case it was set using JavaScript.

  @Watch('myObject')
  parseMyObjectProp(newValue: string | object) {
    if (newValue) {
      this.myInnerObject = typeof newValue === 'object' ? newValue : JSON.parse(newValue);
    }
  }


来源:https://stackoverflow.com/questions/56669642/stencil-object-properties-are-not-set-when-they-provided-through-the-html-strin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!