Ik moet verschillende html weergeven op basis van een bool-variabelen waar of onwaar. Bijvoorbeeld in reageren zou ik zoiets als dit doen in mijn terugkeer in de renderfunctie:
{this.state.booleanValue ? "true" : "false"}
Waar ik twee verschillende uitvoer krijg, afhankelijk van de waarde van booleanValue.
Ik heb het in Polymer 3 geprobeerd en eerst mijn bool-variabele gedeclareerd:
static get properties() { return { myBoolValue: { type: Boolean } }; }
Ik probeer het dan in mijn sjabloon/html te gebruiken als
${this.myBoolValue ? "" : ""}
De code herkent de variabele "this.myBoolValue" echter niet in de html-sjabloon. Hoe kan dat? Volledige code van mijn sjabloon:
static get template() { return html` <div> ${this.myBoolValue ? "true" : "false"} // error, does not recognize "this.myBoolValue". </div> `;
Antwoord
Als uw standaardwaarde van myBoolValue
is false
u kunt uw eigenschappen en sjabloon als volgt wijzigen (Als u voorwaardelijke sjablonen wilt gebruiken, moet u @polymer/polymer/lib/elements/dom-if.js
importeren .)
static get properties() { return { myBoolValue: { type: Boolean, value: false } }; } static get template() { return html` <p>[[myBoolValue]]</p> // OR conditional templates: <template is="dom-if" if="{{myBoolValue}}"> true </template> <template is="dom-if" if="{{!myBoolValue}}"> false </template> `; }
Als u geen standaardwaarde kunt of wilt instellen, wijzigt u uw code als volgt en gebruikt u een berekende eigenschap:
static get properties() { return { myBoolValue: { type: Boolean }, computedBool: { type: String, computed: "_isTrue(myBoolValue)", value: false } }; } static get template() { return html` <p>[[computedBool]]</p> <template is="dom-if" if="{{computedBool}}"> true </template> <template is="dom-if" if="{{!computedBool}}"> false </template> `; } _isTrue(a) { return a === true; }