3

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?

Alex
  • 4,621
  • 1
  • 20
  • 30
  • Stencil does not parse anything other than `boolean` or `number`, so at best you would be getting a string. Does it work if you change the type to `string`? – Thomas Jun 19 '19 at 14:27
  • 1
    @Thomas According to this example https://stenciljs.com/docs/javascript#watching-props-changes it should parse objects too. Strings work fine, but I don't want to pare JSON manually. – Alex Jun 19 '19 at 14:35

1 Answers1

5

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);
    }
  }
Thomas
  • 8,426
  • 1
  • 25
  • 49