I am trying to fill a ion-select in IONIC from data that i get from my backend at the start of the application. This is the JSON i recive:
[{"codRole":15,"codEvent":43},{"codRole":15,"codEvent":45}]
And this is the ion-select:
[
The code:
import {Component,} from '#angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {ZEUS_URL} from "../../properties/properties";
import {Http} from '#angular/http';
import {Rol} from "../../models/Rol";
import {Evento} from "../../models/Evento";
import {RolEvento, RolEventoJSON} from "../../models/RolEvento";
import {FormBuilder, FormControl, FormGroup} from "#angular/forms";
/**
* Generated class for the RolePage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-role',
templateUrl: 'role.html',
})
export class RolePage {
AMform: FormGroup;
Name = new FormControl("");
roles: Rol[];
eventos: Evento[];
rolEventos: RolEvento[];
rolAdmin: boolean = false;
constructor(public http: Http, public navCtrl: NavController, public navParams: NavParams, fb: FormBuilder) {
/**Getting events*/
this.http.get(ZEUS_URL + '/evento/fetch', {withCredentials: true}).map(res => res.json()).subscribe(data => {
this.eventos = new Array<Evento>();
data.forEach(element => {
let temp_event = new Evento(element.codEvento, element.codigo, element.descripcion, element.json_plantilla);
this.eventos.push(temp_event);
})
})
/**Getting roles*/
this.http.get(ZEUS_URL + '/rol/fetch', {withCredentials: true}).map(res => res.json()).subscribe(data => {
this.roles = new Array<Rol>();
data.forEach(element => {
let temp_rol = new Rol(element.codRol, element.nombre, element.descripcion, element.eventos);
this.roles.push(temp_rol);
})
})
/**Getting Events from Roles*/
this.http.get(ZEUS_URL + '/rolEventoSuscripcion/fetch', {withCredentials: true}).map(res => res.json()).subscribe( data => {
this.rolEventos = Array<RolEvento>();
data.forEach(element => {
let temp_rolEventos = new RolEvento(element.codRol, element.codEvento);
this.rolEventos.push(temp_rolEventos);
})
for (var i = 0; i <= this.roles.length - 1; i++) {
console.log(this.rolEventos[i])
this.Name.setValue(this.rolEventos[i]);
}
}, err => {
console.log("Error", err)
})
let numRol: number = parseInt(localStorage.getItem('codRol'));
if (numRol === 15) {
this.rolAdmin = true;
}
}
//Versión usando modelo RolEvento
guardar() {
var resultado: RolEventoJSON[] = [];
for (var i = 0; i <= this.roles.length - 1; i++) {
if (typeof this.roles[i].eventos == "undefined") continue;
for (var j = 0; j <= this.roles[i].getEventos().length - 1; j++) {
resultado.push({codRol:this.roles[i].getCodRol(), codEvento:this.roles[i].getEventos()[j].getCodEvento()})
}
}
console.log(resultado)
console.log(JSON.stringify(resultado))
this.http
.post(ZEUS_URL + "/suscripcion", JSON.stringify(resultado),{withCredentials: true})
.subscribe(data => {
console.log("ok")
}, error => {
console.log("error");
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad RolePage');
}
}
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Conf. de roles</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form>
<ion-list>
<ion-item *ngFor="let rol of roles">
<ion-label>{{rol.nombre}}</ion-label>
<!-- Cada input necesita un modelo (no uno para todos) -->
<ion-select [(ngModel)]="rol.eventos" multiple="true">
<ion-option [value]="evento" *ngFor="let evento of eventos" >{{evento.descripcion}}</ion-option>
</ion-select>
</ion-item>
</ion-list>
<button ion-button icon-right block outline color="botones" (click)="guardar()" type="submit">
Guardar/Submit
<ion-icon name="checkmark-circle-outline"></ion-icon>
</button>
</form>
</ion-content>
The code (doesn't run because its need the data from the backend).
I would like to have checked "ion-option" depending of data from JSON.
Like i am showing a json with only the codes, and not the names, here is the relation:
ROLES TABLE:
'15','ADMIN'
'16','TRAFICO'
'17','RRHH'
'18','ADMINISTRACION'
USERS TABLE:
'43','ALTA TIPO VEHICULO'
'45','BAJA TIPO VEHÍCULO'
Thanks for all!!!
Related
enter image description here
import { Component, OnInit,ViewChild, Input, Output, EventEmitter, ViewEncapsulation } from '#angular/core';
import { LoginService } from 'src/app/services/login.service';
import Swal from 'sweetalert2';
import { NgxSpinnerService } from 'ngx-spinner';
import { MatTableDataSource } from '#angular/material/table';
import { MatPaginator } from '#angular/material/paginator';
import { MatDialog } from '#angular/material/dialog';
import { MatSnackBar } from '#angular/material/snack-bar';
import { FormBuilder, FormGroup, NgForm, Validators, FormArray, FormControl } from '#angular/forms';
#Component({
selector: 'app-historique',
templateUrl: './historique.component.html',
styleUrls: ['./historique.component.css'],
encapsulation: ViewEncapsulation.Emulated
})
export class HistoriqueComponent implements OnInit
{
// #Input('rating') public rating: number[] = [];
// #Input('starCount') public starCount: number = 5;
#Input('color') public color: string = 'accent';
#Output() public ratingUpdated = new EventEmitter();
public snackBarDuration: number = 2000;
public ratingArr : number[] = [];
Questions: any = [];
listDeReponses: any[] = [];
starCount: number = 5;
rating: number = 0;
etoile: string='star_border';
selectedRow :any;
myForm = new FormGroup({
bouton: new FormControl('', [Validators.required]),
// icon: new FormControl('', [Validators.required])
});
constructor(private _loginService: LoginService,public spinner: NgxSpinnerService,public dialog: MatDialog,public snackBar: MatSnackBar) { }
ngOnInit(): void
{
// console.log("a "+this.starCount)
for (let index = 1; index <= this.starCount; index++)
{
this.ratingArr.push(index);
}
var mat = localStorage.getItem('matricule');
var matricule1 = mat!.replace('"', '');
var matricule = matricule1.replace('"', '');
var for1 = localStorage.getItem('formation');
var form = for1!.replace('"', '');
var formation = form.replace('"', '');
this._loginService.GetQuestionsByFormation(matricule,Number(formation)).subscribe(
data =>
{
this.Questions = data;
});
}
onClick(rating:number, quest: number) //
{
this.rating = rating;
console.log(rating);
this.snackBar.open('You rated ' + this.rating + ' / ' + this.starCount, '', {
duration: this.snackBarDuration
});
// this.ratingUpdated.emit(this.rating);
// // this.listDeReponses.push(quest,rating);
// console.log(this.listDeReponses);
return false;
}
showIcon(i: number) //,index:any
{
// this.selectedRow =i;
// console.log(index);
if (this.rating >= i + 1) {
return 'star';
} else {
return 'star_border';
}
}
}
export enum StarRatingColor
{
primary = "primary",
accent = "accent",
warn = "warn"
}
<li *ngFor="let quest of Questions">
<button mat-icon-button [color]="color" *ngFor="let ratingId of ratingArr;index as i" [id]="'star_'+i" (click)="onClick(i+1,3)" matTooltip="ratingId+1" matTooltipPosition="above">
<mat-icon *ngIf="this.etoile=='star_'+i">
{{showIcon(i)}}
</mat-icon>
</button>
<br>
<br>
<button mat-icon-button [color]="color" *ngFor="let ratingId of ratingArr;index as i" [id]="'star_'+i" (click)="onClick(i+1,2)" matTooltip="ratingId+1" matTooltipPosition="above">
<mat-icon *ngIf="this.etoile=='star_'+i" >
{{ showIcon(i) }}
</mat-icon>
</button>
</li>
I have a list of buttons with mat-icon inside, so when a want to change one of them they change all
I expect to change only the button I want to change
there is code html and typescript, hope it will help to understand
I have a list of buttons with mat-icon inside, so when a want to change one of them they change all
I expect to change only the button I want to change
there is code html and typescript, hope it will help to understand
I have a series of questions which have radio answer choices. I can't figure out how to use angular validation to require the user to select all answer before clicking save & next.
NOTE: Please note that click save & next button gets the next 5 question from the controller depending on what choice was made. It's basically a dynamic questionnaire. Below is my code.
<ion-content id="testmodeCont" >
<div class="midCont mrgn0" >
<form #f="ngForm" class="login">
<div class="formCont">
<div *ngIf = "questionCategory == 'Diabetes'">
<div class="boxInCont" *ngFor="let question of AllQuestions | slice:numberOfQuestionsToDisplay:numberOfQuestionsToleft; let i = index">
<div *ngIf="mLanguageFlag === 'English'" >
<div class="heading" *ngIf="question.QuestionType=='dropdown'||question.QuestionType=='radio'||question.QuestionType=='toggle'|| question.QuestionType=='multiselect' ">
Q. {{question.QuestionText}}
</div>
</div>
<div *ngIf="mLanguageFlag === 'English'">
<div class="row mrgnB20" *ngIf="question.QuestionType=='radio'">
<div>
<div class="quetxt">
<ion-list radio-group [ngModelOptions]="{standalone: true}" [(ngModel)]="AllGroupAnswers[i].ExpectedAnswerId" >
<ion-item class="opteach" *ngFor="let answer of question.ExpectedAnswers">
<ion-label class="radioBox fr">{{answer.Answer}}
</ion-label>
<ion-radio item-left [value]="answer.ExpectedAnswerId" (ionSelect)="ValueChanged(answer)">
</ion-radio>
</ion-item>
</ion-list>
</div>
</div>
</div>
</div>
<div *ngIf="mLanguageFlag === 'English'">
<ion-item class="row" *ngIf="question.QuestionType=='dropdown'">
<ion-select formControlName="option" okText="Okay" cancelText="Nah" placeholder= "{{'personal.select'|translate}}" interface = "alert">
<ion-option *ngFor="let answer of question.ExpectedAnswers" [value]="answer.Answer" (ionSelect)="ValueChanged(answer)">{{answer.Answer}}
</ion-option>
</ion-select>
</ion-item>
</div>
</div>
</div>
</div>
</form>
</div>
<div class ="testbtn">
<ion-grid>
<ion-row>
<ion-col align-self-center>
<button ion-button block color="button-color" class="prevBtn" type="submit" (click) = "previous()" *ngIf="previousState" >{{"Previous" | translate}}</button>
</ion-col>
<ion-col align-self-end>
<button ion-button block color="button-color" class="saveBtn" type="submit" (click) = "next()" *ngIf="isDataLoad" >{{"Save & Next" | translate}}</button>
</ion-col>
</ion-row>
</ion-grid>
</div>
ts file
import { Component } from '#angular/core';
import { NavController, NavParams, AlertController, ToastController } from 'ionic-angular';
import { UserService } from '../../providers/service/share';
import { Service } from '../../providers/service/service';
import { Functions } from '../../providers/service/functions';
import { Values } from '../../providers/service/values';
import { UtilService } from '../../providers/service/util';
import { FeedsPage } from '../feeds/feeds';
import { TestPage } from '../test/test';
#Component({
templateUrl: 'testmode.html',
})
export class TestmodePage {
questionCategory: any
ckeckedArray: any;
answersID: any;
userPrefernce: any;
AllQuestions: any;
edittest: any;
testQuestionList: any;
TestQuestions: any;
lifestyleAnswers: any;
AllGroupAnswers: any;
AllTestAnswer: any;
ShowlifeStyleSave: boolean = false;
ExpectedAnswers: any;
mLanguageSelect: any;
mLanguageClass: any;
mLanguageFlag: any;
mLanguageClassdisc: any;
mLanguageClassWhite: any;
mLanguageClassGreen: any;
success: any;
numberOfQuestionsToDisplay: any;
numberOfQuestionsToleft: any
previousState: boolean = false;
isDataLoad: boolean = false;
pageIndex: any;
testform: FormGroup;
constructor(public navCtrl: NavController,public alertCtrl: AlertController,private toastCtrl: ToastController, public navParams: NavParams, public functions: Functions, public values: Values, public utilServices: UtilService, public userService: UserService, public service: Service) {
this.numberOfQuestionsToDisplay = 0;
this.numberOfQuestionsToleft = 5;
this.questionCategory = this.navParams.get('questionCategory')
this.mLanguageFlag = 'English';
this.testQuestionList = [];
this.TestQuestions = [];
this.lifestyleAnswers = [];
this.AllGroupAnswers = [];
this.AllTestAnswer = [];
this.ExpectedAnswers = [];
this.AllQuestions = [];
this.pageIndex = 0 ;
console.log(this.questionCategory);
this.setTestInfo();
}
ionViewDidLoad(){
this.mLanguageSelect = this.userService.getLocaleDisplayName();
console.log(this.mLanguageSelect)
if(this.mLanguageSelect == 'english'){
this.mLanguageClass = ' ';
this.mLanguageFlag='English';
this.mLanguageClassWhite = ' ';
this.mLanguageClassGreen = ' ';
}else if(this.mLanguageSelect == 'hindi'){
this.mLanguageClass = 'heading2';
this.mLanguageClassWhite = 'heading3';
this.mLanguageFlag='Hindi';
this.mLanguageClassGreen = 'heading4';
}
}
setTestInfo(){
var url = '/api/JM_TestQuestions?userId=1002&questionCategory='+ this.questionCategory ;
this.service.jivaGetMethod('1234567899','mobile',url).then((results) => {
console.log(results);
this.userService.setLifeStyleInfo(results);
this.edittest = this.userService.getLifeStyleInfo();
console.log("Your question",this.edittest);
this.AllQuestions = this.edittest.TestQuestions;
console.log("Your answer", this.AllQuestions);
for (var i = 0; i < this.AllQuestions.length; i++) {
// console.log("hello", this.AllQuestions[i]);
var obj= this.AllQuestions[i]
this.AllTestAnswer[i] = obj.ExpectedAnswers;
console.log(this.AllTestAnswer[i]+ i);
this.TestQuestions.push(obj);
console.log(this.TestQuestions.push(obj));
if (obj.ExpectedAnswers[0].UserAnswer==true){
this.AllGroupAnswers.push(obj.ExpectedAnswers[0]);
}else if(obj.ExpectedAnswers[1].UserAnswer==true){
this.AllGroupAnswers.push(obj.ExpectedAnswers[1]);
}else {
this.AllGroupAnswers.push({});
}
console.log("working");
this.testQuestionList.push(obj);
this.isDataLoad = true;
}
})
.catch((error)=>{
console.log(error);
})
}
ValueChanged(answer){
console.log(answer);
console.log(this.AllQuestions) ;
for (var i = 0; i < this.AllQuestions.length; i++) {
if (this.AllQuestions[i].QuestionId==answer.QuestionId) {
for (var j = 0; j < this.AllQuestions[i].ExpectedAnswers.length; j++) {
console.log(this.AllQuestions[i].ExpectedAnswers[j].Answer);
if (this.AllQuestions[i].ExpectedAnswers[j].ExpectedAnswerId==answer.ExpectedAnswerId) {
console.log('match-->',this.AllQuestions[i].ExpectedAnswers[j].ExpectedAnswerId,'-------',answer.ExpectedAnswerId);
this.AllQuestions[i].ExpectedAnswers[j].UserAnswer=true;
console.log(this.AllQuestions[i].ExpectedAnswers[j]);
}else {
console.log('not match-->',this.AllQuestions[i].ExpectedAnswers[j].ExpectedAnswerId,'-------',answer.ExpectedAnswerId);
this.AllQuestions[i].ExpectedAnswers[j].UserAnswer=false;
}
}
break;
}
}
}
submitTest(){
console.log(this.testQuestionList);
var TestQuestions = this.testQuestionList ;
var testData = {
"User": {
"UserId": 79163,
"FirstName": null,
"LastName": null,
"MobileNo": null,
"EmailId": null,
"UserSfdcId": null,
"FacebookId": null,
"GooglePlusId": null,
"AccessToken": null,
"AuthType": null,
"UserLanguage": null,
"UserDeviceId": null,
"UserPersonalDetails": null,
"CountryCode": 0
},
"TestQuestions": TestQuestions
};
this.functions.presentLoading(this.values.lan.WaitTitle);
// var identity = this.userService.getUserIdentity();
// var authtype = this.userService.getUserData().AuthType;
var url = 'http:///api/JM_TestQuestions';
this.service.submitSetUser1('1234567899','mobile',url,JSON.stringify(testData)).then((results) => {
console.log(results);
this.success = results
console.log(this.success);
this.functions.dismissLoading();
//this.navCtrl.setRoot(TestresultsPage);
}) .catch((error)=> {
alert("Please try after sometime..");
this.functions.dismissLoading();
})
}
next(){
this.previousState = true;
console.log(this.AllQuestions.length)
console.log(this.numberOfQuestionsToleft)
if(this.AllQuestions.length > this.numberOfQuestionsToleft) {
this.pageIndex++;
console.log(this.pageIndex)
this.numberOfQuestionsToDisplay = this.numberOfQuestionsToDisplay +5;
this.numberOfQuestionsToleft = this.numberOfQuestionsToleft + 5;
console.log(this.numberOfQuestionsToDisplay);
console.log(this.numberOfQuestionsToleft);
this.submitTest();
} else {
this.submitTest();
let toast = this.toastCtrl.create({
message: 'Your answer for ' + this.questionCategory + ' test was saved successfully',
duration: 2000,
position: 'top'
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
this.navCtrl.setRoot(FeedsPage);
}
}
previous() {
this.pageIndex--;
console.log(this.pageIndex)
this.numberOfQuestionsToDisplay = this.numberOfQuestionsToDisplay - 5;
this.numberOfQuestionsToleft = this.numberOfQuestionsToleft - 5;
console.log(this.numberOfQuestionsToDisplay);
console.log(this.numberOfQuestionsToleft);
this.submitTest();
if(this.pageIndex == 0){
console.log(this.pageIndex)
this.previousState = false;
}
}
ionViewWillLeave(){
let alert = this.alertCtrl.create({
title: "Jiva Ayurveda",
message: "Do you want to close the test ?",
buttons:[
{
text:"Yes",
handler: () => {
this.navCtrl.setRoot(TestPage);
}
},
{
text:"No",
handler: () => {
}
}
]
});
alert.present();
}
}
You can use a (click)=function(arg1, arg2) in order to create a function to check the specific validation you need to see happening.
Edit:
In the function you call with (click) add a logic at the beginning:
function(arg1) {
if(!arg1){
return; // eventually output a string in an error message to indicate the user needs to input or tick a box
} else {
// next page
}
}
use formgroup and initialize form like
this.loginForm = this.fb.group({
username: ['', Validators.required],
password: ['', Validators.required]
})
I'm trying to get data from a api but I cannot print the values in the app. doesn't read the json correctly. not sure what I did wrong..any help for would be helpful. I need to be able to parse down in the json to get the strat_name
this is my code
home.ts:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { RestApiProvider } from '../../providers/restapi/restapi';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
names: string[];
errorMessage: string;
descending: boolean = false;
order: number;
column: string = 'name';
constructor(public navCtrl: NavController, public rest: RestApiProvider) { }
ionViewDidLoad() {
this.getNames();
}
getNames() {
this.rest.getNames()
.subscribe(
names => this.names = names,
error => this.errorMessage = <any>error
);
}
sort() {
this.descending = !this.descending;
this.order = this.descending ? 1 : -1;
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Name List
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-searchbar [(ngModel)]="terms"></ion-searchbar>
<button ion-button type="button" (click)="sort()">Sort</button>
<h1>{{names | json}}</h1>
<ion-item *ngFor="let c of names | search : terms | sort: {property: column, order: order}">
<h2>{{c.strat_name}}</h2>
</ion-item>
</ion-content>
restapi:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';
#Injectable()
export class RestApiProvider {
private apiUrl = 'https://macrostrat.org/api/v2/defs/strat_names?all';
constructor(public http: HttpClient) {
console.log(this.apiUrl);
}
getNames(): Observable<string[]> {
return this.http.get(this.apiUrl).pipe(
map(this.extractData),
catchError(this.handleError)
);
}
private extractData(res: Response) {
let body = res;
return body || {};
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const err = error || '';
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
not sure what I did wrong..any help for would be helpful. I need to be able to parse down in the json to get the strat_names.
first, it loads the json
once I click on search
There are multiple issue in your code
1.Your data is coming like { success : { data : array} } so to access data you need to do below
private extractData(res: any) {
if (res && res.success && res.success.data) {
return res.success.data;
}
return [];
}
2.In your html you need to access the properties like this
<ion-item *ngFor="let n of names">
<h2>{{n?.strat_name}}</h2>
</ion-item>
3.Your data is too much and cause a lot of delays to show the data
After all of that fixes it will look like below
https://stackblitz.com/edit/ionic-jb6ni9
I am using Ionic to create an iOS and android App, I have a list view that displays name of a website and url from a json file. I am displaying the json just fine but I am getting an error in testing in the DevApp on my iPhone. it say cannot GET/myURLString from my json. it displays the url string.
Here is what I have. Can someone help, Im connected to wifi and the url in the address bar says after i click the listview item. localhost:8102/www.myjsonblahblah.net
my resources.html
<ion-header>
<ion-navbar>
<ion-title>Resources & Information</ion-title>
</ion-navbar>
</ion-header>
<ion-item><p text-wrap>Our Resources page will offer adding new resources and finding a team your area.</p></ion-item>
<ion-buttons>
<button ion-button full large color="secondary" style="color: #000000;">Add a resource!</button>
<button ion-button full large color="secondary" style="color: #000000;">Find a team in your area!</button>
</ion-buttons>
<ion-list>
<button ion-item detail-none *ngFor="let item of filteredList" (click)="openWebpage(item.post.URL)">
<h4 text-wrap>{{item.post.Name}}</h4>
<p>{{item.post.URL}}</p>
</button>
</ion-list>
</ion-content>
my resource.ts file
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { DataProvider } from '../../providers/data/data';
import { InAppBrowser, InAppBrowserOptions } from "#ionic-native/in-app-browser";
#IonicPage()
#Component({
selector: 'page-resources',
templateUrl: 'resources.html',
})
export class ResourcesPage {
url: any;
tournments: any[];
filteredList = [];
listType = 'all';
constructor(
private navCtrl: NavController,
private dataProvider: DataProvider, private inAppBrowser: InAppBrowser) {
this.dataProvider.getResource().subscribe((data: any) => {
this.tournments = data.posts;
this.filteredList = this.tournments;
this.url = data.posts;
});
}
openWebpage(url: string) {
const options: InAppBrowserOptions = {
zoom: 'yes',
toolbar: 'yes',
enableViewportScale: 'yes',
}
// Opening a URL and returning an InAppBrowserObject
const browser = this.inAppBrowser.create(url, '_system', options);
console.log(url);
console.log(browser);
console.log("link viewed");
// Inject scripts, css and more with browser.X
}
/**
* open Resoures detail page
*
* #param tournament
*/
openResourcePage(tournament: any) {
this.navCtrl.push('ResourceDetailPage', {tournament: tournament});
}
/**
* search by text
*/
onSearch(event: any) {
const searchText = event.target.value.toLowerCase();
this.filteredList = this.tournments.filter(item => {
if ((item.post.NAME as string).toLowerCase().indexOf(searchText) > -1) {
return true;
}
return false;
});
}
segmentChanged(event: any) {
this.dataProvider.getResource(event.value).subscribe((data: any) => {
this.tournments = data.posts;
this.filteredList = this.tournments;
});
}
}
Somebody please help me. I am trying to filter a JSON data but it does not working and also don't show an error.
i have read the ionic Documentation, but it just work for an array data.
this is my ts file
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
//untuk membaca file json
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
//navigasi ke tampilPage
import { TampilPage } from '../tampil/tampil';
//panggil provider
import { AlQuranProvider } from '../../providers/al-quran/al-quran';
#Component({
selector: 'page-al-quran',
templateUrl: 'al-quran.html',
})
export class AlQuranPage {
searchQuery: string = '';
public alquranTerfilter: string[];
constructor(
private quranProvider: AlQuranProvider,
private http: Http,
public navCtrl: NavController,
public navParams: NavParams) {
}
ionViewDidLoad(){
this.quranInitializeItems();
}
quranInitializeItems(){
this.quranProvider.getQuran().subscribe(
(respon) => {
//this.alquran = respon;
this.alquranTerfilter = respon;
});
}
getItems(ev: any) {
// Reset items back to all of the items
this.quranInitializeItems();
// set val to the value of the searchbar
var val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.alquranTerfilter = this.alquranTerfilter.filter((item) => {
return (item.toString().toLowerCase().indexOf(val.toString().toLowerCase()) > -1);
})
}
}
tampilkan(item){
this.navCtrl.push(TampilPage, {item: item});
}
}
//this.alquran = respon;
/*
if (val && val.trim() != '') {
this.alquranTerfilter = this.alquranTerfilter.filter((item) => {
return (item.toString().toLowerCase().indexOf(val.toString().toLowerCase()) > -1);
})
}
*/
<!--
Generated template for the AlQuranPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>AlQuran</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
<ion-list>
<ion-item *ngFor="let item of alquranTerfilter" (click)="tampilkan(item)">
<h2>{{item.judul}}</h2>
<h4>{{item.riwayat}}</h4>
<ion-icon name="arrow-forward" item-end></ion-icon>
</ion-item>
</ion-list>
</ion-content>
and this the provider
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the AlQuranProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class AlQuranProvider {
// public alquran: string[];
//public alquranTerfilter: string[];
constructor(public http: HttpClient, private httpnonclient: Http) {
}
getQuran(){
return this.httpnonclient.get('./assets/nash/tbQuran.json')
.map(respon => respon.json());
}
}
the filter doesn't working and doesn't showing any error.
sorry for my bad english.
I guess it's a search function right ? Try this
getItems(ev: any) {
this.quranInitializeItems();
var val = ev.target.value;
if (val && val.trim()) {
this.alquranTerfilter = this.alquranTerfilter.filter(
item => item.toString().toLowerCase().includes(val.toString().toLowerCase())
)
} else {
return [];
}
}
I didn't get your filter logic, and you forgot to return something in case your query is empty.