Skip to content

Instantly share code, notes, and snippets.

@surdu
Last active August 22, 2018 12:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save surdu/57ad41764c714c86497b92e1b4cde04e to your computer and use it in GitHub Desktop.
Save surdu/57ad41764c714c86497b92e1b4cde04e to your computer and use it in GitHub Desktop.
ngIf for vanilla JS + NativeScript

What ?

This is the equivalent of using ngIf in angular + {N}, but for vanilla JS + {N}

Why ?

As opposed to using visibility attribute, this will not add the component specified in the template to the view, so the hidden component's loaded event won't be triggered until the component is shown.

const {CustomLayoutView, Property, View, layout} = require("tns-core-modules/ui/layouts/layout-base");
class Render extends CustomLayoutView {
constructor() {
super();
this.viewAdded = false;
}
refresh() {
if (this.when) {
this._addView(this.template);
this.viewAdded = true;
}
else if (this.viewAdded) {
this._removeView(this.template);
this.viewAdded = false;
}
}
onLayout(left, top, right, bottom) {
if (this.when) {
View.layoutChild(this, this.template, 0, 0, right - left, bottom - top);
}
}
onMeasure(widthMeasureSpec, heightMeasureSpec) {
if (this.when) {
const result = View.measureChild(this, this.template, widthMeasureSpec, heightMeasureSpec);
const width = layout.getMeasureSpecSize(widthMeasureSpec);
const widthMode = layout.getMeasureSpecMode(widthMeasureSpec);
const height = layout.getMeasureSpecSize(heightMeasureSpec);
const heightMode = layout.getMeasureSpecMode(heightMeasureSpec);
const widthAndState = View.resolveSizeAndState(result.measuredWidth, width, widthMode, 0);
const heightAndState = View.resolveSizeAndState(result.measuredHeight, height, heightMode, 0);
this.setMeasuredDimension(widthAndState, heightAndState);
}
else {
this.setMeasuredDimension(0, 0);
}
}
}
const when = new Property({
name: "when",
affectsLayout: true,
valueChanged: function(target) {
target.refresh();
}
});
when.register(Render);
module.exports = {
Render: Render
};
<Page xmlns:r="path/to/Render"> <!-- file on disk should be "path/to/Render.js" -->
<r:Render when="{{ someCondition === true }}">
<r:Render.template>
<Label text="This will not be added to the view until 'someCondition' is true" />
</r:Render.template>
</r:Render>
</Page>
@shiv19
Copy link

shiv19 commented Aug 22, 2018

Kudos!
This is useful. Thank you! :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment