Pass parameters between routes in nativesscript - nativescript

In a NativeScript app I have two routes as bellow :
{ path : "boxes" , component : BoxesPage } ,
{ path : "card" , component : CardPage } ,
In the BoxesPage I'm trying to pass something to CardPage like this :
constructor ( private _routerExtention : RouterExtensions , private _router : Router) {
}
onItemTap ( _box ) {
let navigationExtras : NavigationExtras = {
queryParams : { 'box' : _box } ,
fragment : 'anchor'
};
this._router.navigate( [ '/card' ] , navigationExtras );
}
Then in the CardPage component :
ngOnInit () : any {
this.route.params.subscribe( ( _box : Box ) => {
console.log( _box ); //undefined or {}
} );
return undefined;
}
Question is :
Is this the right way ?
How should I get my box object inside the CardPage ?
Worth mentioning that I'm using Angular2 withing the NativScript.
I've tried everything but the documentation is extremely poor unfortunately.
Thanks in advance.

if you want to pass complex data(Object) between one component to other component stringify the object and pass it to other component to parse JSON by using object.
app.component.ts:
public appListComponent(item: any) {
const getData: string = item;
const navigationExtras: NavigationExtras = {
queryParams: {
DataList: JSON.stringify(getData)
}
};
this.routerExtensions.navigate(["app-modal"], navigationExtras);
}
app.modal.component.ts:
public constructor(public route: ActivatedRoute) {
this.route.queryParams.subscribe((params) => {
this.getParamData = params["DataList"];
let obj: ModalData = JSON.parse(this.getParamData);
console.log("Name", obj.name);
console.log("Description", obj.description);
});
}
modaldata.ts:
export class ModalData {
name: string;
description: string;
}

You can refer my answer in this similar post: NativeScript + Angular Navigation context . Basically you do this via "route arguments" which are strings. Unfortunately you cannot pass "entire" JS/TS objects but you can implements a service which can retrieve those via the provided string arguments. For roe details and code snippets check my response in the other thread.
Here is a short intro if the other thread:
Passing objects while navigating in Angular + NativeScript is not the same as vanila NativeScript. The routing is entirely implemented via angular specifications which means you will need to use their implementation. The current RC5 version of Angular 2 uses the following navigation (routing).

Related

How to retrieve dropdown items from an observable?

How would you retrieve dropdown items from an observable in #rxweb/reactive-dynamic-forms ?
how do you inject service in FormControlConfig subclass? shared code here https://stackblitz.com/edit/angular-bs5yqt-nmzcwj
For injecting custom services into the dynamic form control source model you have to pass the respective service into the argument of model configuration.
Step 1
Create a Service according to your need, I am creating fake ConfigService.
import { HttpClient} from "#angular/common/http"
import { Injectable } from "#angular/core"
#Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
configUrl = 'assets/config.json';
getConfig() {
return this.http.get(this.configUrl);
}
}
Step 2
Let's create a Model, which is extended with FormControlConfig for async source binding.
import { FormControlConfig } from "#rxweb/reactive-dynamic-forms"
import { ConfigService } from "./config.service"
export class SourceAsyncConditionalModel extends FormControlConfig{
constructor(fieldConfig: { [key: string]: any }, public controlsConfig: { [key: string]: FormControlConfig },notificationId:number,private configService:ConfigService){
super(fieldConfig,controlsConfig,notificationId);
}
filter() {
let promise = new Promise<any>((resolve, reject) => {
/// call the service
if(this.configService)
this.configService.getConfig();
});
}
}
If you see the above the code where I have defined four parameters. The first three parameters are used in FormControlControl and the fourth parameter we can use in the model instance.
Step 3
Now, we have to pass the parameter with respective model. See the below code :
this.dynamicFormConfiguration = {
controlConfigModels: [{ modelName: 'sourceAsync', model: SourceAsyncConditionalModel,arguments:[this.configService] }],
}
this.dynamicFormBuildConfig = this.formBuilder.formGroup(this.serverData, this.dynamicFormConfiguration);
Here is the working Example

load data to grid in angular 6 using http get

Im trying to load the following sample data to jqgrid(free) using http.get in angular 6.
[{"maker":"Toyota", "model":"Celica"},{ "maker": "Chrysler", "model":"Mondeo"}]
Model Class
export class Model{
maker : string
model : string
}
Component:
...
#Component({...})
export class SampleComponent implements OnInit {
private _sampleService;
columnModel : any[];
models : Model[];
constructor(_sampleService : SampleService) {
this._sampleService = _sampleService;
}
ngOnInit() {
this.columnModel = [{ name: "maker" },{ name: "model" }]
this.models = this._sampleService.getModelList().subscribe(models => this.models = models);
}
ngAfterViewInit() {
(<any>jQuery("#grid")).jqGrid({
colModel: this.columnModel,
data: this.models
});
}
}
Service:
....
#Injectable()
export class SampleService{
constructor(private http : HttpClient){}
getModelList():Observable<Model[]>{
return this.http.get<Model[]>
("http://localhost:8090/myapp/getModel");
}
}
If I do the following, I can see the data in the console.
this.http.get("http://localhost:8090/ducksoup/getModel")
.subscribe(data => {console.log(data)})
But,it is not rendering in the grid. Any help?
You can write your jqxGrid binding code inside of OnInit method, right after you fetch your records and it will show your data on datagrid

Cannot initialize the state of ngrx (v. 4.x) store

I am currently looking into using the ngrx store (v. 4.0.3) for state management. It seems like a great project.
I have hit a bit of a bump in the road while trying to initialize the state of my store. The documentation makes it look rather simple, but yet I am not able to see where I am going wrong.
Here's the relevant code snippets:
in app.state.ts
export interface AppState {
searchText: string;
}
In search-text.reducer.ts
export const UPDATE = 'UPDATE';
export class UpdateSearchTextAction implements Action {
readonly type: string = UPDATE;
constructor(public readonly text: string) {}
}
export function searchTextReducer(state: string, action: UpdateSearchTextAction) {
switch(action.type) {
case UPDATE:
return action.text;
}
};
In app.module.ts
export const reducers: ActionReducerMap<AppState, UpdateSearchTextAction> = {
searchText: searchTextReducer
};
export const initialState: InitialState<AppState> = {
searchText: 'sds'
};
....
imports: [
....
StoreModule.forRoot(reducers, initialState)
]
in some Component
constructor(private store: Store<AppState>) {
this.searchBoxText = store.select('searchText');
this.searchBoxText.subscribe(text => console.log('value = [' + text + "]"));
}
So, when the application loads, I would expect to see the following logged to the console:
value = [sds]
yet I see
value = [undefined]
Later, once I start typing in an input that triggers an UpdateSearchTextAction the console does indeed log the correct value. So it seems like I've setup the store correctly.
There is probably something real simple I'm missing. Can anyone provide some advice?
Since you are having it as readonly you are not allowed to assign the value,
export class UpdateSearchTextAction implements Action {
readonly type: string = UPDATE;
constructor(public text: string) {}
}
And you need to dispatch the value using a dispatch statement
this.store.dispatch(new UpdateSearchTextAction.UPDATE(<<string>>));
You must specify default value for state argument and return the same state if no action matches. Try to change your reducer to the following:
export function searchTextReducer(state: string = '', action: UpdateSearchTextAction) {
switch(action.type) {
case UPDATE:
return action.text;
default:
return state;
}
};

Remove buttons md-autofocus from a custom md-dialog

I have a this md-dialog https://codepen.io/patapron/pen/oLaxap
<md-button ng-click="answer('not useful')" >
Not Useful
</md-button>
<md-button ng-click="answer('useful')" style="margin-right:20px;" >
Useful
</md-button>
How do to I get remove the md-autofocus from the buttons?
Objetive: Any button must be pre-selected paint in grey.
There is an easier way to do this without having to write a custom directive. Angular Material has the ability to remove autofocus built-in.
In your controller where you are writing the .show function, set the focusOnOpen to false focusOnOpen: false
The documentation explains it here $mdDialog
Here is an example of how mine looks
function deleteMediaDialog() {
var dialogData = {
};
$mdDialog.show({
controller : 'deleteMediaDialogController',
controllerAs : 'vm',
templateUrl : 'app/main/apps/scala-media/dialogs/delete/delete-dialog.html',
parent : angular.element($document.body),
focusOnOpen : false,
clickOutsideToClose: true,
locals : {
dialogData: dialogData
}
});
}
I solved by mysleft. Directive magic
scope.$watch(function () { return ele.attr('class'); }, function () {
if (ele.hasClass('md-focused')) {
ele.removeClass('md-focused');
}
});

Ckeditor plugin - validating a text field

I am creating plugin
I have this piece of code below:
What i am trying to do is make sure the email address they enter is valid.
Just not sure how to stop the onOK if the email address is not valid.
Thanks
This is a code snippet of the plugin
contents : [
{
id : 'info',
label : editor.lang.form.title,
title : editor.lang.form.title,
elements : [
{
id : 'destEmail',
type : 'text',
label : 'Email form results to:',
'default' : 'randy#me.com',
required : true,
accessKey : 'T',
commit : function( element )
{
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (this.getValue().search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
element.setAttribute('id', this.getValue() );
}
}
]
}
]
Please take a look on official sample and validate property. You can write your own validation method at this point.
You can also use one of the available (still not documented in API). You probably want to do something like this (CKEditor 4):
...
validate: CKEDITOR.dialog.validate.regex( /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i, "Please enter a valid email address." );
...
It is also possible to combine existing validators and/or write custom validators:
function customValidator( x, msg ) {
return function() {
var value = this.getValue(),
pass = !!( CKEDITOR.dialog.validate.integer()( value ) && value < x );
if ( !pass ) {
return msg;
}
};
}
...
validate: customValidator( 5, 'Error message when larger than 5.' )
...

Resources