I'm looking for an open source NS7 replacement for the nativescript-drop-down menu. Does anyone have suggestions. I'm porting my app to NS7 and having trouble finding a replacement for what has gone to a paid version of the plugin.
My workaround was to open a modal that has the dropdown items and then receiving the chosen item in the closeCallback function, like so:
dropdown-modal.xml
<Page ios:class="bg-light" xmlns="http://schemas.nativescript.org/tns.xsd" shownModally="onShownModally">
<StackLayout class="modal-view">
<Label android:class="p-l-10 font-weight-normal font-size-larger" ios:class="h2 font-weight-bold p-l-15 p-t-10" text="{{ title }}"></Label>
<Label class="hr"></Label>
<ScrollView class="page" height="40%">
<ListView class="list-group" itemTap="{{ onItemTap }}" items="{{ data }}">
<ListView.itemTemplate>
<Label android:class="h4 text-center font-weight-bold p-b-10" ios:class="h3 text-center font-weight-bold p-y-10" width="100%" text="{{ value }}"
textWrap="true"></Label>
</ListView.itemTemplate>
</ListView>
</ScrollView>
</StackLayout>
</Page>
Notice the difference between Android and iOS classes. This makes the dropdown more system-like.
dropdown-modal.js
import { DropDownViewModel } from "./dropdown-view-model";
export const onShownModally = function(args) {
const dropDownViewModel = new DropDownViewModel(args.context.title, args.context.list, args.closeCallback);
const page = args.object;
page.bindingContext = dropDownViewModel;
};
dropdown-view-model.js
import { Observable, ObservableArray } from "#nativescript/core";
export class DropDownViewModel extends Observable {
constructor(title, items, closeCallback) {
super();
this.title = title;
this.data = new ObservableArray(items);
this.selectedItem = '';
this.closeCallback = closeCallback;
}
onItemTap(args) {
this.selectedItem = args.view.bindingContext;
this.closeCallback(this.selectedItem);
}
}
And this is how it is called in another page.
sample-page.xml
<!--Roles-->
<StackLayout class="m-y-10 m-x-2" row="2" col="1">
<Label class="far h3 p-l-15 text-black m-b-1" text=" Role" textWrap="true" />
<TextField editable="false" tap="{{ toggleDropdown }}" dataListId="roles" dataName="role" dataTitle="Role" class="h4 fal text-black input-border-rounded-lg" text="{{ role.value }}" />
</StackLayout>
Notice how dataListId, dataName, and dataTitle were passed.
sample-page.js
import { SamplePageViewModel } from "./sample-page-view-model";
const samplePageViewModel = new SamplePageViewModel();
export const onNavigatingTo = async function(args) {
await samplePageViewModel.populateRolesList();
};
export const onNavigatedTo = async function(args) {
const page = args.object;
page.bindingContext = samplePageViewModel;
};
sample-page-view-model.js
import { Frame, Observable } from "#nativescript/core";
import { LookupService } from "~/services/lookupService";
import { AppSettingsUtility } from "~/utilities/appSettingsUtility";
export class SamplePageViewModel extends Observable {
constructor() {
super();
this.lookupService = new LookupService();
this.appSettingsUtility = new AppSettingsUtility();
this.routes = this.appSettingsUtility.getRoutes();
this.roles = [];
this.role = { code: 0, value: '' };
}
async populateRolesList() {
this.set('roles', await this.lookupService.getRoles()); // assume roles list
}
toggleDropdown(args) {
const page = args.object.page;
const that = this;
const options = {
context: { title: args.object.dataTitle, list: that.get(args.object.dataListId) },
closeCallback: (selectedItem) => {
if(selectedItem)
that.set(args.object.dataName, selectedItem);
}
};
page.showModal(this.routes.dropdown, options);
}
}
Related
While using RadAutoCompleteTextView in nativescript-angular app,I'm facing this weird problem:
I build my project using "tns build android --bundle".App starts but RadAutocompleteCompleteTextView shows
"no result found" although data bound to items attribute logs on terminal.
Now,if I make a minor change in my code(like delete a comment),it detect changes and auto rebuild again and this time AutocompleteView shows the data it was binding to.
Also,now if I run my app over usb debugging it runs well but if I remove usb and restart app it shows error
Error:View already has a parent
Here are the html and ts files :
app.component.html
<ActionBar title="Lestrange" class="actionbar" [height]="abarVisible">
<!-- <Image src="~/app/assets/men.png" height='50' width='50'></Image>-->
<NavigationButton icon="~/app/assets/menu.png" (tap)="onOpenDrawerTap()" [visibility]="getMenuVisible ? 'visible' : 'hidden'"></NavigationButton>
<ActionItem class="name" [visibility]="SearchVisible ? 'visible' : 'hidden'">
<StackLayout backgroundColor="#66cdaa" height="60" width="150" #action>
<RadAutoCompleteTextView [items]="searchdata" (didAutoComplete)="onDidAutoComplete($event)" *ngIf="searchdata" #aitem>
<SuggestionView tkAutoCompleteSuggestionView>
<ng-template tkSuggestionItemTemplate let-item="item">
<StackLayout orientation="vertical" padding="10">
<ImageCacheIt [src]="item.image" class='img' height='170' width='100' stretch="fill"></ImageCacheIt>
<Label [text]="item.id"></Label>
</StackLayout>
</ng-template>
</SuggestionView>
</RadAutoCompleteTextView>
</StackLayout>
</ActionItem>
<ActionItem>
<Label text="Search" color="white" (tap)="opensearch()"></Label>
</ActionItem>
</ActionBar>
<RadSideDrawer backgroundColor="transparent" id="rd" [gesturesEnabled]="sideDrawerEnabled">
<GridLayout tkDrawerContent rows="auto, *, auto" class="root-drawer-content">
<StackLayout tkDrawerContent>
<StackLayout height="56" marginTop="50" style="text-align: center; vertical-align: center;">
<Label text="Menu" fontSize="27"></Label>
</StackLayout>
<StackLayout margin="25">
<Label text="Home" [nsRouterLink]="['/hh']" padding="10" (tap)="onCloseDrawerTap()" fontSize="20" class="lbl"></Label>
<Label text="Live" [nsRouterLink]="['/lil']" padding="10" (tap)="onCloseDrawerTap()" fontSize="20" class="lbl"> </Label>
<Label text="Movies" [nsRouterLink]="['/moe']" padding="10" (tap)="onCloseDrawerTap()" fontSize="20" class="lbl"></Label>
<Label text="TV Shows" [nsRouterLink]="['/ss']" padding="10" (tap)="onCloseDrawerTap()" fontSize="20" class="lbl"></Label>
<Label text="Hindi" [nsRouterLink]="['/dhh']" padding="10" (tap)="onCloseDrawerTap()" fontSize="20" class="lbl"></Label>
</StackLayout>
<Label text="Logout" color="lightgray" padding="15" style="horizontal-align: center" (tap)="logout()" fontSize="20"> </Label>
</StackLayout>
</GridLayout>
<page-router-outlet tkMainContent actionBarVisibility="never"></page-router-outlet>
</RadSideDrawer>
app.component.ts:`
import {registerElement} from "nativescript-angular/element-registry";
registerElement("exoplayer", () => require("nativescript-exoplayer").Video);
import { Component,OnInit, ViewChild,AfterViewInit,OnChanges,AfterContentInit} from "#angular/core";
//import { isAndroid } from "tns-core-modules/platform";
import { Page } from "tns-core-modules/ui/page";
import { RouterExtensions } from "nativescript-angular/router";
import * as ApplicationSettings from "#nativescript/core/application-settings";
const firebase = require("nativescript-plugin-firebase");
import { RadSideDrawerComponent} from "nativescript-ui-sidedrawer/angular";
import {FirebaseService} from '../app/services/firebase.service';
import { RadAutoCompleteTextViewComponent } from "nativescript-ui-autocomplete/angular";
import { TokenModel, AutoCompleteCompletionMode, AutoCompleteDisplayMode, AutoCompleteSuggestMode } from "nativescript-ui-autocomplete";
import { ObservableArray } from "tns-core-modules/data/observable-array"
import { Observable } from "rxjs";
import "rxjs/add/operator/merge";
import { MovieModel } from "./models/movie.model";
import { NavigationExtras } from "#angular/router";
#Component({
selector: "ns-app",
templateUrl: "app.component.html"
})
export class AppComponent implements OnInit,AfterViewInit,AfterContentInit{
#ViewChild(RadSideDrawerComponent, { static: false }) public drawerComponent: RadSideDrawerComponent;
public isAuth: boolean;
public sideDrawerEnabled:boolean=false;
public getMenuVisible:boolean=true;
public abarVisible:number=70;
public searchvar: boolean;
public searchdata: ObservableArray<MovieModel>;
public searchdata1: ObservableArray<MovieModel>;
public datas$:Observable<any>;
public SearchVisible: boolean=false;
constructor(private page: Page,public router:RouterExtensions,public firebaseService: FirebaseService) { }
ngAfterContentInit(): void {
}
ngAfterViewInit(): void {
// //ApplicationSettings.setBoolean("authenticated", false);
// console.log(this.searchdata);
// //},2);
}
public ngOnInit() {
firebase.init({
}).then(
() => {
console.log("firebase.init done");
},
error => {
console.log(`firebase.init error: ${error}`);
}
);
/////////////////////////////////////////////////////
// console.log("fir"+this.getMenuVisible);
this.firebaseService.AbarVisibleEnabled.subscribe(x=>this.abarVisible=x);
this.firebaseService.SearchVisibleEnabled.subscribe(x=>this.SearchVisible=x);
this.firebaseService.sideDrawerEnabled.subscribe(x=>this.sideDrawerEnabled=x);
this.firebaseService.MenuVisibleEnabled.subscribe(y=>this.getMenuVisible=y);
// console.log("fir"+this.getMenuVisible);
this.searchdata = new ObservableArray<MovieModel>();
this.datas$ = <any>this.firebaseService.getMyWishList('/index');
// this.searchdata=this.firebaseService.fetchsearchdata();
// this.searchdata1=this.searchdata;
// console.log(this.searchdata);
// // setTimeout(()=>{
this.datas$.subscribe(datas=>{
datas.map(x=>{console.log(x);
this.searchdata.push(new MovieModel(x.id,x.c,x.img));
})
});
//this.drawer = this.drawerComponent.sideDrawer;
if(this.router.router.url==='/login'){
this.isAuth=true;
}else{
this.isAuth=false;
}
}
public onDidAutoComplete(args) {
this.SearchVisible=false;
console.log(args.text.split(",")[0]);
console.log(args.text.split(",")[1].trim());
this.searchvar=false;
let navigationExtras: NavigationExtras = {
queryParams: {
"showId": args.text.split(",")[0].trim(),
"fromRoute":args.text.split(",")[1].trim()
}
};
this.router.navigate(["/show-detail"],navigationExtras);
}
onOpenDrawerTap() {
this.drawerComponent.sideDrawer.showDrawer();
}
onCloseDrawerTap() {
this.drawerComponent.sideDrawer.closeDrawer();
}
get dataItems(): ObservableArray<MovieModel> {
return this.searchdata;
}
opensearch(){
this.SearchVisible=!this.SearchVisible;
}
public logout() {
this.onCloseDrawerTap();
ApplicationSettings.setBoolean("authenticated", false);
//ApplicationSettings.remove("authenticated");
this.router.navigate(["/login"], { clearHistory: true });
}
}
`
Although I don't have much knowledge about angular lifecycle hooks but I have a feeling that its about angular hooks ,So I tried to use differnet hooks but to no avail.Please help me find the issue in my code.Thanks in advance.
It looks like you have an unpaired </StackLayout> tag in your html file. It is right after `.
I think you should remove that and see if that resolves the issue.
Hope this helps!
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);
}
I would like to know if it's possible to have UIScrollView with fade effect with nativescript please ?
For example : https://medium.com/#luisfmachado/uiscrollview-with-fade-effect-246e332e8b24
I read the documentation https://nativescript-vue.org/en/docs/elements/components/scroll-view/, but I don't found this information.
I would like this result for example :
Do you have an idea please ? Thank you
I have no idea how can I put the native code in my component
<template>
<ScrollView class="scroll" orientation="vertical" row="1" ref="scrollView">
<StackLayout marginLeft="10" marginRight="10" class="container-verses">
<StackLayout horizontalAlignment="center">
<Label textWrap="true" textAlignment="center" text="hello" color="#FFFFFF" fontSize="20"/>
...
<Label textWrap="true" textAlignment="center" text="hello" color="#FFFFFF" fontSize="20"/>
</StackLayout>
</StackLayout>
</ScrollView>
</template>
<script>
export default {
name : 'FadeScrollView',
computed: {},
methods : {
//
}
};
</script>
<style lang='scss' scoped>
</style>
Here is how you translate Swift into NativeScript
import { isIOS } from "#nativescript/core/platform";
import { ScrollView } from "#nativescript/core/ui/scroll-view";
let FadeScrollViewImpl;
if (isIOS) {
FadeScrollViewImpl = UIScrollView.extend({
fadePercentage: 0.2,
gradientLayer: CAGradientLayer.new(),
transparentColor: UIColor.clearColor.CGColor,
opaqueColor: UIColor.blackColor.CGColor,
topOpacity: () => {
const scrollViewHeight = this.frame.size.height;
const scrollContentSizeHeight = this.contentSize.height;
const scrollOffset = this.contentOffset.y;
const alpha = (scrollViewHeight >= scrollContentSizeHeight || scrollOffset <= 0) ? 1 : 0;
return UIColor.alloc().initWithWhiteAlpha(0, alpha).CGColor;
},
bottomOpacity: () => {
const scrollViewHeight = this.frame.size.height;
const scrollContentSizeHeight = this.contentSize.height;
const scrollOffset = this.contentOffset.y;
const alpha = (scrollViewHeight >= scrollContentSizeHeight || scrollOffset + scrollViewHeight >= scrollContentSizeHeight) ? 1 : 0
return UIColor.alloc().initWithWhiteAlpha(0, alpha).CGColor;
},
layoutSubviews() {
super.layoutSubviews()
this.delegate = this;
const maskLayer = CALayer.new();
maskLayer.frame = this.bounds;
this.gradientLayer.frame = CGRectMake(this.bounds.origin.x, 0, this.bounds.size.width, this.bounds.size.height);
this.gradientLayer.colors = [this.topOpacity, this.opaqueColor, this.opaqueColor, this.bottomOpacity];
this.gradientLayer.locations = [0, NSNumber.alloc().initWithFloat(this.fadePercentage), NSNumber.alloc().initWithFloat(1 - this.fadePercentage), 1];
maskLayer.addSublayer(this.gradientLayer);
this.layer.mask = maskLayer
},
scrollViewDidScroll(scrollView) {
this.gradientLayer.colors = [topOpacity, opaqueColor, opaqueColor, bottomOpacity];
}
});
}
export class FadeScrollView extends ScrollView {
createNativeView() {
if (isIOS) {
return FadeScrollViewImpl.new();
} else {
return super.createNativeView();
}
}
attachNative() {
if (!isIOS) {
super.attachNative();
}
}
}
Then you just have to register the element to start using it in template
Vue.registerElement('FadeScrollView', () => require('./fade-scrollView').FadeScrollView)
Playground Sample
I am new to nativescript and angular2. I want to filter listview using textfield input entered by user. in angular version 1, we used to do it like
<input type="text" ng-model="userinput">
<div ng-repeat="x in items | filter : userinput">
</div>
how can i do this using angular2 in nativescript?
my listview is:
<ListView [items]="myItems" class="list-group">
<template let-item="item">
<StackLayout>
<Label [text]='item.Department' class="list-group-item"></Label>
</StackLayout>
</template>
</ListView>
and in my component:
export class someComponent {
public myItem: Array<any>;
public isLoading: boolean;
public constructor(private http: Http) {
this.myItem = [];
this.isLoading = true;
}
public ngOnInit()
{
this.http.get("some_api_url")
.map(result => result.json())
.do(result => console.log(JSON.stringify(result)))
.subscribe(result => {
this.myItem = result;
this.isLoading = false;
}, error => {
console.log("ERROR: ", error);
});
}
}
You had to create a pipe for filtering first, something like:
#Pipe({
name: 'filter'
})
#Injectable()
export class FilterPipe implements PipeTransform {
transform(items: any[], field : string, value : string): any[] {
if (!items) return [];
return items.filter(it => it[field] == value);
}
}
Usage:
<li *ngFor="let it of its | filter : 'name' : 'value or variable'">{{it}}</li>
The nativescript ui listview filtering is slow when the data is huge and it does "remove" the no match item. I change a bit code to make it fast and only show filtered data. :)
happy coding :)
Page class="page">
<StackLayout orientation="vertical">
<GridLayout rows="auto,auto,*,auto">
<StackLayout class="form" row="0" orientation="horizontal" width="100%">
<TextField hint="Search..." class="input"
id= "searchstr"
[(ngModel)]="searchstr"
width="80%"></TextField>
<Button class="btn-sm btn-primary btn-active"
id="btnSearch"
(tap)="onSearchTap($event)"
width="20%" height="40" >
<FormattedString>
<Span [text]="iconval" class="icon"></Span>
</FormattedString>
</Button>
</StackLayout>
<StackLayout row="1" orientation="horizontal" width="100%" backgroundcolor="black">
<Label text="CODE" width="25%" class="caption"></Label>
<Label text="NAME" width="75%" class="caption"></Label>
</StackLayout>
<ScrollView row="2" tkExampleTitle tkToggleNavButton>
<RadListView [items]="dataItems"
(itemLoading)="onItemLoading($event)">
<ListViewLinearLayout
tkListViewLayout scrollDirection="Vertical"
itemInsertAnimation="Slide"
itemDeleteAnimation="Slide"></ListViewLinearLayout>
<ng-template tkListItemTemplate let-item="item" let-i="index" let-odd="odd" let-even="even">
<StackLayout class="list-item"
(tap)="onItemTap(item)"
orientation="horizontal" width="100%">
<Label [text]="item.custCode" width="25%"></Label>
<Label [text]="item.custName" width="75%"></Label>
</StackLayout>
</ng-template>
</RadListView>
</ScrollView>
</GridLayout>
</StackLayout>
</Page>
import { Component, OnInit } from '#angular/core';
import { ListViewEventData } from 'nativescript-ui-listview';
import { Color } from 'tns-core-modules/color/color';
import { APIService } from '~/app/core/services';
import { Observable } from 'rxjs';
import { CustProfileLight } from '~/app/core/model';
import { ObservableArray } from 'tns-core-modules/data/observable-array/observable-array';
#Component({
selector: 'ns-customer-lookup',
templateUrl: './customer-lookup.component.html',
styleUrls: ['./customer-lookup.component.css'],
moduleId: module.id,
})
export class CustomerLookupComponent implements OnInit {
private _dataItems: ObservableArray<CustProfileLight>;
customer$:Observable<CustProfileLight>
iconval:string;
search:string;
searchstr:string;
items:any;
//private _myFilteringFunc: (item: any) => any;
constructor(private serv:APIService) { }
ngOnInit() {
this.iconval = String.fromCharCode(0xe986);
this.serv.getCustomer().subscribe(resp=>{
this.items = resp;
this._dataItems = new ObservableArray<CustProfileLight>(resp);
})
}
get dataItems(): ObservableArray<CustProfileLight> {
return this._dataItems;
}
onItemLoading(args: ListViewEventData){
if (args.index % 2 === 0) {
args.view.backgroundColor = new Color("#b3ecff");
}
}
onItemTap(item){
}
onSearchTap(e){
const key =this.searchstr;
console.log(key);
let data= this.items.filter(item=>item.custCode.includes(key) ||
item.custName.includes(key) ||
item.address1.includes(key) ||
item.address2.includes(key) ||
item.address3.includes(key) ||
item.address4.includes(key) ||
item.city.includes(key) ||
item.state.includes(key) ||
item.postalCode.includes(key) ||
item.tel.includes(key) ||
item.fax.includes(key) ||
item.contactPerson.includes(key)
);
this._dataItems = new ObservableArray<CustProfileLight>(data);
}
// get FilteringFunc(): (item: any) => any {
// return this._myFilteringFunc;
// }
// set FilteringFunc(value: (item: any) => any) {
// this._myFilteringFunc = value;
// }
}
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 }