How can I change a Boolean property in Lit-Element to hide content on my component?

两盒软妹~` 提交于 2020-05-15 22:04:40

问题


I have a custom component that should hide content when I set a boolean property to false. Every other property gets reflected except that one. I must be doing something wrong.

static get properties(){
      title: {
        type: String,
        attribute: 'title',
      },

      titleEnable: {
        type: Boolean,
        attribute: 'title-enable',
      },
}

constructor() {
    super();
    this.titleEnable=true;
    this.title="default";
}

render(){

    return html`                
        ${this.titleEnable 
        ? html`
        <p class="title" ?hidden="${!this.titleEnable}">${this.title}</p>
        `
        : html ``} 
    ` 
}

If I use that component like <my-component></my-component> in an HTML file it shows: default as expected.

If I use it like this: <my-component title="New Title"></my-component> it displays: New Title as expected.

BUT if I try to hide it <my-component title-enable="false"></my-component> the boolean just doesn't change. I've tried !title-enable, title-enable='false", .titleEnable=false and all the variants you can imagine. What pisses me the most is that whenever I set in the constructor 'this.titleEnable=false' and I happen to just declare the variable WITHOUT value on the tag and it takes it as TRUE an "default" appears. <my-component title-enable></my-component> I am completely lost.


回答1:


Ok, this is a tricky one. You need to handle it differently by passing some object as below:

  static get properties() {
    return {
      titleConfig: {
        type: Object,
        attribute: 'title-config'
      }
    }
  }

  render() {
    return html`                
      ${this.titleConfig.titleEnable
        ? html`
      <p class="title" ?hidden="${!this.titleConfig.titleEnable}">${this.titleConfig.title}</p>
      `
        : html``} 
  `
  }

In HTML:

<my-component title-config='{"title":"shan", "titleEnable": false}'></my-component>

Now, the question is why it is true every time?

Answer: For a Boolean property to be configurable from markup, it must default to false. If it defaults to true, you cannot set it to false from markup, since the presence of the attribute, with or without a value, equates to true. This is the standard behavior for attributes in the web platform.

It is taken from polymer doc.

So, by creating an attribute title-enable, the HTML considers this attribute as true

It's really a bummer for someone who starts working on Polymer or LitElement .



来源:https://stackoverflow.com/questions/60678891/how-can-i-change-a-boolean-property-in-lit-element-to-hide-content-on-my-compone

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