Nativescript RadListView not binding to source property - telerik

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>

Related

Xamarin: Binding to ImageSource property is not working

I am trying to display images dynamically through binding:
I have ObservableCollection of TabItem to which I load a png into the Icon Property:
TabItems.Add(new TabItem()
{
Title = AppResources.Home,
IsSelected = true,
Icon = ImageSource.FromResource("Home.png")
});
Where:
public class TabItem : BindableObject
{
private bool _isSelected;
public ImageSource Icon { get; set; }
public string Title { get; set; }
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
if (_isSelected != value)
{
_isSelected = value;
OnPropertyChanged();
}
}
}
}
And I have a DataTemplate of TabItem in a CollectionView that displays these items and uses the Icon Property to bind to Image:
<DataTemplate x:DataType="local:TabItem" x:Key="TabItem_DataTemplate">
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
WidthRequest="{Binding Title, Converter={StaticResource ProportionateConverter}}"
>
<Image Source="{Binding Icon}" InputTransparent="True" HeightRequest="50" />
<Label HorizontalOptions="Center" VerticalOptions="End" FontSize="Small"
Text="{Binding Title}"
InputTransparent="True"
TextColor="{Binding IsSelected, Converter={StaticResource IsSelectedToTextColorConverter}}"/>
</StackLayout>
</DataTemplate>
I get an Error in runtime:
ImageLoaderSourceHandler: Image data was invalid: Xamarin.Forms.StreamImageSource
The images are in the Resources folder and are marked as Embedded resource
Updated solution:
(Thanks Jason)
The solution was using my markup extension when initializing the Icon property (I'll be glad to hear of a more elegant way)
var homeExt = new ImageResourceExtension()
{
Source = "TimeManager.Resources.Icons.Home.png"
};
TabItems.Add(new TabItem()
{
Title = AppResources.Home,
IsSelected = true,
Icon = (ImageSource)(homeExt.ProvideValue(null))
});

How to Expand only one item in collapsible list with NativeScript

I have built a RadListview with nativescript. But now I want that if I tap on an item then only that item should open and other Expanded items should close.
I followed this Creating a collapsible list with NativeScript and it works, I just need one item expanding at a time
enter image description here
thank you
export class RoadComponent {
public roads: Array<any>;
constructor(private page:Page,private router: Router, private roadService: RoadService,private back:BackendService) {
}
async ngOnInit() {
this.roads = await this.roadService.getRoads();
}
templateSelector(item: any, index: number, items: any): string {
return item.expanded ? "expanded" : "default";
}
onItemTap(event: ListViewEventData) {
var listView = event.object as RadListView,
rowIndex = event.index,
dataItem = event.view.bindingContext;
dataItem.expanded = !dataItem.expanded; listView.androidListView.getAdapter().notifyItemChanged(rowIndex);
}
}
<Page>
<StackLayout>
<RadListView multipleSelection="false" id="abc" height="100%" [items]="roads" [itemTemplateSelector]="templateSelector" class="list-group" (itemTap)="onItemTap($event)">
<ng-template tkListItemTemplate let-item="item">
<StackLayout id="abc" orientation="vertical">
<Label text="{{item.name}}" class="list-group-item">
</Label>
</StackLayout>
</ng-template>
<ng-template tkTemplateKey="expanded" let-item="item">
<GridLayout rows="auto,auto" columns="*,*" class="list-group-item add-dropdown">
<Label row="0" col="0" text="{{item.name}}" class="list-group-item"></Label>
<Button row="1" col="0" text="{{item.id}}" (tap)="navigatetomap(item.name)" [nsRouterLink]="['/accueil', { outlets: { homeoutlet: ['home'] } }]"></Button>
<Button row="1" col="1" text="{{item.name}}"></Button>
</GridLayout>
</ng-template>
</RadListView>
</StackLayout>
</Page>
if anyone had this issue just make expanded property false to all the items
onItemTap(event: ListViewEventData) {
for(let i=0;i<this.roads.length;i++){
this.roads[i].expanded=false;
}
var listView = event.object as RadListView,
rowIndex = event.index,
dataItem = event.view.bindingContext;
dataItem.expanded = !dataItem.expanded;
listView.androidListView.getAdapter().notifyItemChanged(rowIndex);
}

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

Binding does not work with StackLayout

That works and the value of cnt is displayed:
<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="loaded">
<Label text="{{ cnt }}" />
</Page>
That does not display the value of cnt:
<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="loaded">
<StackLayout>
<Label text="{{ cnt }}" />
</StackLayout>
</Page>
The model is:
var observable = require("data/observable");
var upDownViewModel = new observable.Observable({cnt: 0});
module.exports = upDownViewModel;
And loaded is:
exports.loaded = function(args) {
var page = args.object;
page.bindingContext = model;
}
The problem is that the Label needs a height to work with the StackLayout if a data binding is used.

How to add delete button and making it work in 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;
}
});
};

Resources