How to add delete button and making it work in nativescript - nativescript

I'm trying to add a delete button and making it work, i'm splitting up the problems in two.
In my xml file I have this:
<Page loaded="onPageLoaded">
<GridLayout rows="auto, *">
<StackLayout orientation="horizontal" row="0">
<TextField width="200" text="{{ task }}" hint="Enter a task" id="task" />
<Button cssClass="test" text="Add" tap="add"></Button>
<Button cssClass="test" text="Refresh" tap="refresh"></Button>
</StackLayout>
<ListView items="{{ tasks }}" row="1">
<ListView.itemTemplate>
<Label text="{{ name }}" />
<Button cssClass="test" text="X" tap="delbutton"></Button>
</ListView.itemTemplate>
</ListView>
</GridLayout>
</Page>
The first problem is the delbutton, which is the delete button, if i add it like that it will replace my view with a bunch of X's. I cant seem to understand why.
The second problem i'm having trouble with is how to make it work so that it loops through and deletes the item i want to delete, what im cyrrently doing is getting data form a backend server with json that looks like this:
exports.onPageLoaded = function(args) {
page = args.object;
pageData.set("task", "");
pageData.set("tasks", tasks);
page.bindingContext = pageData;
var result;
http.request({
url: "http://192.168.1.68:3000/posts.json",
method: "GET",
headers: { "Content-Type": "application/json" },
}).then(function (response) {
result = response.content.toJSON();
for (var i in result) {
tasks.push({ name: result[i].name });
}
}, function (e) {
console.log("Error occurred " + e);
});
};
exports.delbutton = function() {
console.log("REM")
};
Thanks for your help and time.

The first problem (that only the X is showing) is due to the fact that a ListView item wants exactly one (1) child. You have two (a Label and a Button). Fortunately one item might be a so what you want to do is to enclose your two elements in a StackLayout, like this:
<Page loaded="onPageLoaded">
<GridLayout rows="auto, *">
<StackLayout orientation="horizontal" row="0">
<TextField width="200" text="{{ task }}" hint="Enter a task" id="task" />
<Button cssClass="test" text="Add" tap="add"></Button>
<Button cssClass="test" text="Refresh" tap="refresh"></Button>
</StackLayout>
<ListView items="{{ tasks }}" row="1">
<ListView.itemTemplate>
<StackLayout orientation="horizontal">
<Label text="{{ name }}" />
<Label text="{{ hello }}" />
<Button cssClass="test" text="X" tap="delbutton"></Button>
</StackLayout>
</ListView.itemTemplate>
</ListView>
</GridLayout>
</Page>
As for the second part of removing items from the ListView. I don't know if your pageData is an observable object as the declaration is not part of your pasted code, but I'm guessing it is. Anyways, I've created an example of how to populate data using observables (which is the NativeScript way of building ui:s, see previous link) and how to remove an item from the ListView.
I've added comments in the code to explain what I'm doing.
var Observable = require('data/observable');
var ObservableArray = require('data/observable-array');
/**
* Creating an observable object,
* see documentation: https://docs.nativescript.org/bindings.html
*
* Populate that observable object with an (empty) observable array.
* This way we can modify the array (e.g. remove an item) and
* the UI will reflect those changes (and remove if from the ui
* as well).
*
* Observable objects are one of NativeScripts most fundamental parts
* for building user interfaces as they will allow us to
* change an object and that change gets propagated to the ui
* without us doing anything.
*
*/
var contextArr = new ObservableArray.ObservableArray();
var contextObj = new Observable.Observable({
tasks: contextArr
});
exports.onPageLoaded = function(args) {
var page = args.object;
page.bindingContext = contextObj;
/**
* Simulating adding data to array after http request has returned json.
* Also adding an ID to each item so that we can refer to that when we're
* removing it.
*/
contextArr.push({name: 'First Item', id: contextArr.length});
contextArr.push({name: 'Second Item', id: contextArr.length});
contextArr.push({name: 'Third Item', id: contextArr.length});
};
exports.delbutton = function(args) {
/**
* Getting the "bindingContext" of the tapped item.
* The bindingContext will contain e.g: {name: 'First Item', id: 0}
*/
var btn = args.object;
var tappedItemData = btn.bindingContext;
/**
* Iterate through our array and if the tapped item id
* is the same as the id of the id of the current iteration
* then remove it.
*/
contextArr.some(function (item, index) {
if(item.id === tappedItemData.id) {
contextArr.splice(index, 1);
return false;
}
});
};

Related

How do I update or refresh a RadListView item on iOS platform?

I have a RadListView that gets data from an Observable Array of objects and displays its content as text.
When modify one of the value of the object in the Observable Array, the RadListView does not refresh or update the value, even with radlist.refresh();
On Android :android: platform, this is not an issue, it works and refreshes fine, but on iOS platform it does not.
Here is my XML code
```<lv:RadListView items="{{ groceryList }}" id="marad" row="1" height="100%"
itemSwipeProgressStarted="onSwipeCellStarted" swipeActions="true">
<lv:RadListView.itemTemplate>
<GridLayout class="grocery-list-item">
<Label
id="nameLabel" textWrap="true" class="p-15 radlist" text="{{ 'ناو: ' + name + '\n' + ' بڕ: ' + quantity + '\n' + ' نرخی یەک دانە: ' + sellPrice }}" />
</GridLayout>
</lv:RadListView.itemTemplate>
<lv:RadListView.headerItemTemplate>
<StackLayout>
<Button class="btn btn-primary" text="خوێندنه‌وه‌ بە باڕکۆد" tap="barcodeSell"></Button>
<Label class="page-placeholder" text="نرخی گشتی" textWrap="true"/>
<Label
text="0"
id="totalprice"
textWrap="true"
class="input input-border"/>
<Button class="btn btn-primary" text="بفرۆشە" tap="tapSell"></Button>
</StackLayout>
</lv:RadListView.headerItemTemplate>
<lv:RadListView.itemSwipeTemplate>
<GridLayout columns="auto, *, auto">
<GridLayout id="increase-view" col="2" tap="onIncrease"
class="increase-view">
<Label
text="" class="fonticon duplic" />
</GridLayout>
<GridLayout id="delete-view" col="0" tap="onDelete"
class="delete-view">
<Label
text="" class="fonticon duplic" />
</GridLayout>
</GridLayout>
</lv:RadListView.itemSwipeTemplate>
</lv:RadListView>```
Here is my 'modify the value' function in JS:
exports.onIncrease = function (args) {
var item = args.view.bindingContext;
var index = groceryList.indexOf(item);
var totalPrice = groceryList.getItem(index).sellPrice;
var element = groceryList.getItem(index);
var quantity = groceryList.getItem(index);
var quantity3 = quantity["quantity"];
dialogs.prompt({
message: "بڕی کاڵاکە دیاریبکە",
okButtonText: "هەڵبژێرە",
cancelButtonText: "داخە",
inputType: dialogs.inputType.number
}).then(function (r) {
if(r.result) {
element["quantity"] = r.text;
groceryList.setItem(index, element);
sumPrice = (sumPrice - (Number(totalPrice)*Number(quantity3)));
sumPrice = sumPrice + (Number(r.text)*Number(totalPrice));
label.text = sumPrice;
radlist.refresh();
}
else {
var rslt = false;
}
});
};
Here is the code which feeds the RadListView:
function onNavigatingTo(args) {
const page = args.object;
label = page.getViewById("totalprice");
const sideDrawer = app.getRootView();
sideDrawer.gesturesEnabled = false;
spanquantity = page.getViewById("quantbtn");
groceryList = new ObservableArray([
]);
pageData = observableModule.fromObject({
groceryList: groceryList,
});
page.bindingContext = pageData;
radlist = page.getViewById("marad");
sumPrice = 0;
}
exports.onNavigatingTo = onNavigatingTo;
And then an item data is pushed to the Observable Array if the input barcode was found the database, but this is not related to this issue, I'm saying these to make the code clear.
One more thing, if I swipe RadListView and tap delete item button, it deletes the item fine, so, in the case of delete button, it updates and refreshes the list, I guess.
So, this issue is related to the increase item quantity process.

OnBlur event without the ngModel & textfield blinking

Nativescript app: I am creating dinamy TextFields.
1) Probme - When i tap on dinamicly generated text field, the keyboard shows for miliseconds and the disapears. When i tap really fast a few times then the keyboard stays.
2) How to make onChange/onBlur event on dinamicly generated TextField? Like when i update the textField i need to call a method.
Here is the current list:
(blur) Does not work:
<StackLayout col="1" row="0">
<ListView [items]="categoryService.attributes | async">
<template let-item="item" let-i="index">
<GridLayout rows="50 100">
<Label [text]="item.name"></Label>
<TextField #input *ngIf="item.type=='text'" row="1" hint="Enter Value here" [text]="item.name" (blur)="categoryService.onAttributeChange(item, item.type, null, input.value)"></ TextField>
<Switch #switch *ngIf="item.type=='checkbox'" row="1" checked="false" (checkedChange)="categoryService.onAttributeChange(item, item.type, null, switch.checked)"></Switch>
<DropDown #aa
*ngIf="item.type=='select'"
row="1"
[items]="categoryService.showAttributeValues(item.value)"
[selectedIndex]="selectedIndex"
(selectedIndexChange)="categoryService.onAttributeChange(item, item.type, aa.selectedIndex)"></DropDown>
</GridLayout>
</template>
</ListView>
</StackLayout>
Thanks!
About your second question you could use textChange method and to return $event as argument this will help you to get text for every TextField individually. You could review the sample code below. About the problem with showing the keyboard, it could be something related with the listview itemTap event. However this problem has been reproduced only on Android and still looking for possible solution.
app.component.html
<StackLayout>
<ListView [items]="myItems" (itemTap)="onItemTap($event)">
<template let-item="item" let-i="index" let-odd="odd" let-even="even">
<StackLayout [class.odd]="odd" [class.even]="even">
<Label [text]='"index: " + i'></Label>
<Label [text]='"[" + item.id +"] " + item.name'></Label>
<TextField (tap)="onTap($event)" hint="Enter text" text="" (textChange)="ontextChange($event)"></TextField>
</StackLayout>
</template>
</ListView>
</StackLayout>
app.component.ts
import {Component, Input, ChangeDetectionStrategy} from '#angular/core';
import {TextField} from "ui/text-field";
import app = require("application");
class DataItem {
constructor(public id: number, public name: string) { }
}
#Component({
selector: "my-app",
templateUrl: "app.component.html",
})
export class AppComponent {
public myItems: Array<DataItem>;
private counter: number;
public status =true;
constructor() {
this.myItems = [];
this.counter = 0;
for (var i = 0; i < 50; i++) {
this.myItems.push(new DataItem(i, "data item " + i));
this.counter = i;
}
}
public onItemTap(args) {
console.log("------------------------ ItemTapped: " + args.index);
}
public ontextChange(args){
console.log("text "+args.object.text);
}
}
I hope this helps

RadListView better scrollToIndex() behavior

RadListView.scrollToIndex() seems to display the selected item at the bottom of the current window always - regardless of whether the item is already visible or not.
Is there a function like RadListView.isVisible()?
I have just tested the given scenario with scrollToIndex() and was unable to reproduce such a behavior. Selected row has been always displayed in the top of the screen. You could review my sample code.
main-page.xml
<Page loaded="onPageLoaded" xmlns:lv="nativescript-telerik-ui-pro/listview" xmlns="http://www.nativescript.org/tns.xsd">
<lv:RadListView id="rdid" loaded="radlistviewlaoded" items="{{ dataItems }}" >
<lv:RadListView.listViewLayout>
<lv:ListViewLinearLayout scrollDirection="Vertical"/>
</lv:RadListView.listViewLayout>
<lv:RadListView.itemTemplate>
<StackLayout orientation="vertical">
<Label fontSize="20" text="{{ itemName }}"/>
<Label fontSize="14" text="{{ itemDescription }}"/>
</StackLayout>
</lv:RadListView.itemTemplate>
</lv:RadListView>
</Page>
main-page.ts
import { EventData } from "data/observable";
import { Page } from "ui/page";
import { HelloWorldModel } from "./main-view-model";
import { ObservableArray } from "data/observable-array";
import { RadListView } from "nativescript-telerik-ui-pro/listview";
import {setTimeout} from "timer"
// Event handler for Page "navigatingTo" event attached in main-page.xml
export function onPageLoaded(args: EventData) {
// Get the event sender
var page = <Page>args.object;
var listview:RadListView = <RadListView> page.getViewById("rdid");
console.log("listview visibility "+listview.visibility);
//listview.scrollToIndex(3);
var array = new ObservableArray();
for(var i=0;i<20;i++){
array.push({itemName:"Name "+i, itemDescription:"desc "+i});
}
setTimeout(function(){
listview.scrollToIndex(3)
}, 2000)
page.bindingContext = {dataItems:array};
}
export function radlistviewlaoded(args:EventData){
console.log("RadListView loaded");
}
About the second question you could use loaded event in case you want to know when the view has been loaded on the screen. In case you would like to know if the RadListview is visible you could use visibility property.

Nativescript RadListView not binding to source property

I am trying to implement {N} telerik's UI RadListView. Here is their getting started guide, which I followed as a reference.
I have setup the following XML layout :
list.xml
<StackLayout loaded="loaded" xmlns:lv="nativescript-telerik-ui/listview" xmlns="http://www.nativescript.org/tns.xsd">
<lv:RadListView items="{{ rankingsArray }}">
<lv:RadListView.listViewLayout>
<lv:ListViewLinearLayout scrollDirection="vertical"/>
</lv:RadListView.listViewLayout>
</lv:RadListView>
<lv:RadListView.itemTemplate>
<StackLayout orientation="horizontal" horizontalAlignment="center" class="sl_ranking">
<Label text="{{ name }}"></Label>
</StackLayout>
</lv:RadListView.itemTemplate>
</StackLayout>
Basically I am binding the list view to a rankingsArray containing child elements which have a name property.
In fact here is how I do the binding :
list.js
var HashtagList = require("~/viewmodels/HashtagsList");
exports.loaded = function(args){
var hashtagList = new HashtagList();
var profile = args.object;
profile.bindingContext = hashtagList;
}
HashtagList is class defined as :
var Hashtag = require("~/classes/Hashtag");
var ObservableModule = require("data/observable-array");
class HashtagList{
constructor(){
}
get rankingsArray(){
if(!this._list){
this._list = new ObservableModule.ObservableArray();
this._list.push(new Hashtag("#pizzawithfriends"));
this._list.push(new Hashtag("#funky"));
}
return this._list;
}
}
module.exports = HashtagList;
As you can see any HashtagList object has a public rankingsArray property which returns an observable array of Hashtag objects.
Here is the definition of the Hashtag object:
hashtag.js
"use strict";
var Hashtag = function(name){
var _name = name;
//====== NAME GETTER & SETTER ======//
Object.defineProperty(this,"name",{
get : function(){
return _name;
},
set : function(value){
_name = value;
}
})
}
module.exports = Hashtag;
The problem is that for some reason I get the following error :
Binding: Property: 'name' is invalid or does not exist. SourceProperty: 'name'
and nothing appears on the screen.
This is weird because if I can access HashtagList.rankingsArray.getItem(0).name without problems.
What is causing this behavior?
Turns out I closed the label tag in the wrong way...
WRONG WAY
<lv:RadListView.itemTemplate>
<StackLayout orientation="horizontal" horizontalAlignment="center" class="sl_ranking">
<Label text="{{ name }}"></Label>
</StackLayout>
</lv:RadListView.itemTemplate>
RIGHT WAY
<lv:RadListView.itemTemplate>
<StackLayout orientation="horizontal" horizontalAlignment="center" class="sl_ranking">
**<Label text="{{ name }}" />**
</StackLayout>
</lv:RadListView.itemTemplate>

TextChange in repeater nativescript

i trying do to textchange in repeater and research this link.
Basic blur event in a Telerik Nativescript Mobile App
It work in single textfield but no work in repeater. Isn't set wrong anything?
XML:
<Repeater id="lstSelectedItemsSingle" items="{{itemsSingle}}">
<Repeater.itemTemplate>
<GridLayout columns="auto,*,auto,*,auto" rows="auto,auto,1" padding="6" id = "{{ matchId + dataType + 'GridSingle'}}">
<GridLayout columns="*,*,*" rows="40" col="3" borderRadius="6" borderWidth="1" borderColor="#DBDBDB" >
<button backgroundImage="res://reduce_enable" style="background-repeat:no-repeat;background-position: 50% 50%" backgroundColor="#BFBFBF" />
<TextField col="1" backgroundColor="#ffffff" col="1" text="{{stake}}" style="text-align:center" keyboardType="number" />
<button backgroundImage="res://add_icon_enable" col="2" style="background-repeat:no-repeat;background-position: 50% 50%" backgroundColor="#BFBFBF" col="2"/>
</GridLayout>
</GridLayout>
</Repeater.itemTemplate>
</Repeater>
Model:
exports.onPageLoaded = function(args){
page = args.object;
viewM.set("stake", "2");
viewM.addEventListener(observable.Observable.propertyChangeEvent, function (event) {
console.log(event.propertyName);
}
});
}
It's probably because repeaters are bound to a list of items - usually observables. If you bind inside the repeater using "{{ }}", NativeScript is going to look for that method on that specific object in the repeater. So your code should be structured something like this (TypeScript) ...
import { Observable, EventData } from 'data/observable';
import { Page } from 'ui/page';
class Item extends Observable({
text: string = '';
constructor(text: string) {
this.text = text;
this.todos.on(ObservableArray.changeEvent, (args: any) => {
// handle text change
});
}
});
class ViewModel extends Observable({
items: ObservableArray<Items>
constructor() {
this.items = new ObservableArray<Items>({
new Item('Thing 1'),
new Item('Thing 2')
});
}
});
let loaded = (args: EventData) => {
let page = <Page>args.object;
page.bindingContext = new ViewModel();
}
export { loaded }

Resources