Skip to content

Instantly share code, notes, and snippets.

@shiv19
Forked from surdu/README.md
Created August 22, 2018 12:15
Show Gist options
  • Save shiv19/944d9f7976d6da96036068e32f0c5255 to your computer and use it in GitHub Desktop.
Save shiv19/944d9f7976d6da96036068e32f0c5255 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment