How to creat a dynamic text - ionic-framework

I have a list of titles, and I would like these texts to alternate as I switch to ion-select. How do I do this?
I have no idea how to do this, not even what part of the code to show. I made an attempt here but whenever I use the console the value returned is undefined.
My typescrit code:
import { Titulo } from './../Services/services.service';
import { DataService } from './data.service';
import { Component, OnInit, ViewChild} from '#angular/core';
import {IonSlides} from '#ionic/angular';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-libertacao',
templateUrl: './libertacao.page.html',
styleUrls: ['./libertacao.page.scss'],
})
export class LibertacaoPage implements OnInit {
#ViewChild(IonSlides) slides: IonSlides;
PAGINA_SELECIONADA: number;
// tslint:disable-next-line: variable-name
index_atual: number;
titulo: Titulo;
constructor(private dataservice: DataService, private activatedRoute: ActivatedRoute ){
}
ngOnInit() {
const id = this.activatedRoute.snapshot.paramMap.get('id');
this.titulo = this.dataservice.getTituloById(parseInt(id, 10));
}
OnChange(event: any)
{
if (event.detail.value === this.PAGINA_SELECIONADA) {
this.slides.slideTo(this.PAGINA_SELECIONADA);
}
else {}
console.log(this.titulo);
}
slideChanged() {
this.slides.getActiveIndex().then((index) => {
this.index_atual = index;
});
}
}

Related

Add Components dynamically in DOM ionic+angular

I am following How to Dynamically Create a Component in Angular to add components dynamically inside another component. I am receiving a weired error of undefined variable.
My Component file (MessComponent)
<template #messContainer>
<p>
mess works!
</p>
</template>
ts file
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-mess',
templateUrl: './mess.component.html',
styleUrls: ['./mess.component.scss'],
})
export class MessComponent implements OnInit {
constructor() { }
ngOnInit() {}
}
Parent Component (hosting dynamic component)
module ts file
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { CommonModule } from '#angular/common';
import { IonicModule } from '#ionic/angular';
import { FormsModule } from '#angular/forms';
import { HomePage } from './home.page';
import { HomePageRoutingModule } from './home-routing.module';
import { MessComponent } from './../mess/mess.component';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
HomePageRoutingModule
],
declarations: [HomePage, MessComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
entryComponents: [MessComponent]
})
export class HomePageModule {}
ts file
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef, ComponentFactory, OnInit } from "#angular/core";
import { MessComponent } from "./../mess/mess.component";
#Component({
selector: "app-home",
templateUrl: "home.page.html",
styleUrls: ["home.page.scss"],
})
export class HomePage implements OnInit {
componentRef: any;
#ViewChild('messContainer', { read: ViewContainerRef, static: true }) entry: ViewContainerRef;
createComponent() {
this.entry.clear();
const factory = this.resolver.resolveComponentFactory(MessComponent);
this.componentRef = this.entry.createComponent(factory);
}
destroyComponent() {
this.componentRef.destroy();
}
constructor(private resolver: ComponentFactoryResolver) {}
ngOnInit(): void {
this.createComponent();
}
}
and the error I am receiving
Uncaught (in promise): TypeError: this.entry is undefined
I understand this is claiming regarding the variable entry, but don't understand why it is not identifying that variable. To conclude, why I cannot add the component?
Solved it. Actually I was passing wrong param to the #ViewChild(''). I was passing the template name (container) of the child while I should have passed the container name in the parent component. So created a div in the parent component with #messContainer and corrected the #ViewChild
Important!:
now #messContainer is in the parent component and everything works as expected.
#ViewChild('messContainer', { read: ViewContainerRef, static: true }) entry: ViewContainerRef;

Rest web service returns null value on mobile device but works on PC in Ionic App

i am consuming Rest JSONP Web Service in an ionic App which works fine on PC but returns null value on mobile devices
My page.ts file
import {
Component,
OnInit
} from '#angular/core';
import {
AlertController,
LoadingController
} from '#ionic/angular';
import {
ActionSheetController
} from '#ionic/angular';
import {
Router
} from '#angular/router'
import {
ProApiService
} from './../../../../services/pro-api.service';
#Component({
selector: 'app-ranked-diagnosis',
templateUrl: './ranked-diagnosis.page.html',
styleUrls: ['./ranked-diagnosis.page.scss'],
})
export class RankedDiagnosisPage implements OnInit {
tabSelect: string = 'show10';
show10Data: Array < any >= [];
showAllData: Array < any >= [];
redFlagsData: Array < any >= [];
loading: any;
constructor(
private api: ProApiService,
public alertController: AlertController,
public loadingController: LoadingController,
public actionSheetController: ActionSheetController,
private router: Router
) {}
segmentChanged(event: any) {
this.tabSelect = event.detail.value;
}
async presentActionSheet(buttons) {
const actionSheet = await this.actionSheetController.create({
header: 'Sub Diagnosis',
buttons: buttons
});
await actionSheet.present();
}
async presentAlert(msg: string, header: string) {
const alert = await this.alertController.create({
header: '',
subHeader: header,
message: msg,
buttons: ['OK']
});
await alert.present();
}
async presentLoading() {
this.loading = await this.loadingController.create({
message: 'loading...',
});
return await this.loading.present();
}
ngOnInit() {
}
ionViewWillEnter() {
if (this.api.ProApiData.diagnoses_checklist.diagnoses) {
this.showAllData =
this.api.ProApiData.diagnoses_checklist.diagnoses;
for (let i = 0; i < 10; i++) {
this.show10Data.push(this.showAllData[i]);
}
this.showAllData.forEach(item => {
if (item.red_flag == 'true') {
this.redFlagsData.push(item);
}
});
console.log(this.showAllData);
} else {
console.log('error');
this.router.navigateByUrl('isabel-pro');
}
}
why_diagnosis(url: any, weightage: any) {
this.presentLoading();
this.api.why_diagnosisApi(url).subscribe(res => {
let matched_terms = res._body.why_diagnosis.matched_terms;
console.log(matched_terms);
let alertMsg = `We matched the terms: ${matched_terms}<br><hr>Degree of match between query entered and database: ${weightage}`;
this.presentAlert(alertMsg, 'Why did this diagnosis come up ?');
this.loadingController.dismiss();
}, err => {
this.loadingController.dismiss();
console.log('error');
});
}
}
in the above code i am calling why_diagnosis function which calls the function from a service file.
My service.ts file
import {
Injectable
} from '#angular/core';
import {
HttpClient,
HttpHeaders
} from '#angular/common/http';
import {
Jsonp
} from '#angular/http';
import {
Observable
} from 'rxjs';
import {
map
} from 'rxjs/operators';
import {
ConstantsService
} from './../../../services/constants.service';
#Injectable({
providedIn: 'root'
})
export class ProApiService {
apiRoot = this.root.APIroot;
diagnosisPROData: any;
drugData: any;
ProApiData: any;
drugApiData: any;
constructor(
private jsonp: Jsonp,
private http: HttpClient,
private root: ConstantsService) {}
why_diagnosisApi(url: any): Observable < any > {
let whyUrl = `${this.apiRoot}Mob_isabelPRO.php?
why_url=${url}&callback=JSONP_CALLBACK`;
return this.jsonp.request(whyUrl, 'callback')
.pipe(
map(
res => {
let why_diagnosis = res;
return why_diagnosis;
}
)
);
}
}
above code is from my service file.
this is the value i am getting in PC
this is the return on mobile
i dont know whats wrong with it. please suggest me the solution
Thanks

I have assigned an object during ionViewDidLoad, but the object still empty

I am new to Ionic, I have this problem when trying to pass navParams to other pages. I want to pass the team object from TeamHomePage to TeamDetailPage. but I always got the null. I have check in the ionViewDidLoad, and console it to make sure the team object is assigned, and try to pass a testing object (successfully). Anyone has any idea when is the object of the team went?
<ion-tabs>
<ion-tab tabTitle="Team" [root]='teamDetailTab' [rootParams]='testing' tabIcon="basketball"></ion-tab>
<ion-tab tabTitle="Standings" [root]='standingsTab' [rootParams]='team' tabIcon="podium"></ion-tab>
</ion-tabs>
TeamHomePage.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { TeamDetailPage } from '../team-detail/team-detail';
import { StandingsPage } from '../standings/standings';
#Component({
selector: 'page-team-home',
templateUrl: 'team-home.html',
})
export class TeamHomePage {
public team: any = {}
public teamDetailTab = TeamDetailPage
public standingsTab = StandingsPage
public testing: any = {id:1, content: 'testing'}
constructor(
public navCtrl: NavController,
public navParams: NavParams) {}
ionViewDidLoad() {
this.team = this.navParams.data
console.log('TeamHomePage navParams.data:')
console.log(this.navParams.data)
console.log('TeamHomePage this.team:')
console.log(this.team)
}
goHome() {
this.navCtrl.popToRoot()
}
}
TeamDetailPage.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { EliteApi } from '../../providers/elite-api/elite-api';
import { GamePage } from '../game/game';
import * as _ from 'lodash'
#Component({
selector: 'page-team-detail',
templateUrl: 'team-detail.html',
})
export class TeamDetailPage {
public team: any = {}
public games: any[]
private tourneyData: any
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private eliteApi: EliteApi
) {}
ionViewDidLoad() {
this.team = this.navParams.data
this.tourneyData = this.eliteApi.getCurrentTourney()
this.games = _.chain(this.tourneyData.games)
.filter(g => g.team1Id === this.team.id || g.team2Id === this.team.id)
.map(g => {
let isTeam1 = (g.teamId === this.team.id)
let opponentName = isTeam1 ? g.team2: g.team1
let scoreDisplay = this.getScoreDisplay(isTeam1, g.team1Score, g.team2Score)
return {
gameId: g.id,
opponent: opponentName,
time: Date.parse(g.time),
location: g.location,
locationUrl: g.locationUrl,
scoreDisplay: scoreDisplay,
homeAway: (isTeam1 ? "vs.": "at")
}
})
.value()
console.log('TeamDetail team:')
console.log(this.navParams.data)
console.log('TeamDetail: tourneyData')
console.log(this.tourneyData)
console.log('TeamDetail touerneyData.games:')
console.log(this.tourneyData.games)
}
getScoreDisplay(isTeam1, team1Score, team2Score) {
if (team1Score && team2Score) {
var teamScore = (isTeam1 ? team1Score : team2Score)
var opponentScore = (isTeam1 ? team2Score : team1Score)
var winIndicator = teamScore > opponentScore ? 'W: ' : 'L: '
return winIndicator + teamScore + '-' + opponentScore
}else {
return ''
}
}
Empty Team Object showing in console chrome

Use property as form validator in Angular2 (data-driven)

I'm having a hard time trying to set a max value using the data driven approach in Angular2.
I want to set the max value of the input to a property called userLimit, which I get from firebase. This is my code:
component.ts
import { Component, OnInit, AfterViewInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from "#angular/forms";
import { FiredbService } from '../services/firedb.service';
import { AuthService } from '../services/auth.service';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
#Component({
selector: 'my-dashboard',
styleUrls: ['./recibirpago.component.scss'],
templateUrl: './recibirpago.component.html'
})
export class RecibirpagoComponent implements OnInit, AfterViewInit {
myForm2: FormGroup;
uid: string;
userLimit: any;
constructor(private fb: FormBuilder,
private dbfr: FiredbService,
private db: AngularFireDatabase,
private authService: AuthService) {
this.myForm2 = this.fb.group({
email: ['', Validators.email],
clpmount: ['', [Validators.required, Validators.max(this.userLimit)]]
});
}
ngOnInit() {
this.uid = this.authService.getUserUid();
}
ngAfterViewInit() {
this.dbfr.getUserLimit(this.uid).subscribe(snapshot => {
this.userLimit = snapshot.val().accountLimit;
console.log(this.userLimit);
})
}
If I write, for example, Validators.max(5000) it works, but if I try to get the data from Firebase it doesn't work.
Thanks for your help!
The problem is that the constructor is executing before the ngAfterViewInit so you don't have the value of the userLimit at that point.
Instead use the setVAlidators method within the subscribe where you get the data.
Something like this:
constructor
this.myForm2 = this.fb.group({
email: ['', Validators.email],
clpmount: ['', Validators.required] // <-- not here
});
ngAfterViewInit
ngAfterViewInit() {
this.dbfr.getUserLimit(this.uid).subscribe(snapshot => {
this.userLimit = snapshot.val().accountLimit;
console.log(this.userLimit);
const clpControl = this.myForm2.get(`clpmount');
clpControl.setValidators(Validators.max(this.userLimit)); // <-- HERE
clpControl.updateValueAndValidity();
})
}
NOTE: Syntax was not checked.

passing parameter between pages ionic

Hi i´m new in ionic and I am trying to pass the scann information form one page to another, the thing its that when I execute the program I have a console.log to check if the info its passed correctly but on chrome console said undefined, letme paste my code:
home.ts where i try to send the info from the scan:
import { Component } from '#angular/core';
import { NavController,Platform } from 'ionic-angular';
import { BarcodeScanner } from '#ionic-native/barcode-scanner';
import { TabsPage } from '../tabs/tabs';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
private barcodeText:String;
private barcodeFormat:String;
private platform:Platform;
private navController:NavController;
constructor(private barcodeScanner: BarcodeScanner,public navCtrl: NavController,platform:Platform) {
this.platform = platform;
this.navController = navCtrl;
}
doScan(){
console.log('scannig product barcode');
this.platform.ready().then(() => {
this.barcodeScanner.scan().then((result) => {
if (!result.cancelled) {
this.barcodeText = result.text;
this.scanningDone(this.barcodeText)
}
}, (error) => {
console.log('error when scanning product barcode');
});
});
}
scanningDone(data){
this.navController.push(TabsPage,{
data:data
});
}
main.ts where the info suppose to go:
import { Component } from '#angular/core';
import { NavController, NavParams , ToastController} from 'ionic-angular';
import { BarcodeScanner } from '#ionic-native/barcode-scanner';
import { DetailsPage } from '../details/details';
import { Http } from '#angular/http'
#Component({
selector: 'main',
templateUrl: 'main.html'
})
export class MainPage {
information: any[];
item:any;
private bcData;
constructor(public navCtrl: NavController, private http: Http,public params:NavParams) {
this.bcData = params.get('data');
console.log(params.get('data'));
let localData = http.get(this.bcData).map(res => res.json().items);
localData.subscribe(data => {
this.information = data;
})
}
on the console.log(params.get('data')); its where I get the undefinied on the console.
you could have a method in your TabsPage that handles opening and closing pages like this:
openPages(Page, Data){
this.navCtrl.push(Page,Data);
}
Then in your scanningDone Method:
scanningDone(data){
this.tabsPage.openPages(MainPage,{
data:data
});
}
How about using localStorage
look at this as well