Ionic 2/3 : How to programmatically uncheck a check box - ionic2

I have a situation wherein I have to uncheck a checkbox, onclick of a button.
This is my checkbox code
<ion-checkbox [checked]="!isChecked" [disabled]="!isdisabled" (ionChange)="saveProfile($event)" [(ngModel)]="default"></ion-checkbox>
I have tried using !iChecked, but it doesn't work. Basically, if the checkbox is already checked by the user, I want it to be unchecked (based on certain conditions) when you click a button.
<button class="button-m" (click)="navigateTo()" ion-button color="secondary"><ion-icon name="next"> </ion-icon> Next </button>
TS file
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ToastController } from 'ionic-angular';
#Component({
selector: 'choose-profile',
templateUrl: 'choose-profile.html',
})
export class ChooseProfilePage {
profileValue : string;
isdisabled : boolean;
isChecked :boolean;
constructor(public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController) {
}
getSelectedProfile(val){
this.profileValue = val;
if(this.profileValue!=undefined){
this.isdisabled = true;
}
else{
this.isdisabled = false;
}
}
saveProfile(val){
if(val.checked==true)
{
this.presentToast( this.profileValue+"set as default profile")
}
else
{
this.presentToast("No default profile")
}
}
presentToast(val){
let toast = this.toastCtrl.create({
message: val,
duration: 3000,
position: 'top'
});
toast.present();
}
navigateTo()
{
console.log("Next Clicked")
this.isChecked == true;
}
}

You have an error in your code. this.isChecked == true; does not set the isChecked variable to true. It merely does a comparison to check if isChecked is true.
You should use = instead of ==.
Alter your code to be as following:
navigateTo()
{
console.log("Next Clicked")
this.isChecked = true;
}

Don't use the checked attribute as a binding. Your input is bound with ngModel so what you need to do is change the value of that field.
I'm surprised after fixing the double equals your code worked because the template is looking for default and sets the checked attribute based on it's value. Create a variable and bind to it, then change it. I rewrote your component a bit
And then in your component:
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ToastController } from 'ionic-angular';
#Component({
selector: 'choose-profile',
templateUrl: 'choose-profile.html',
})
export class ChooseProfilePage {
public shouldSaveProfile = false;
profileValue : string;
isdisabled : boolean;
constructor(public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController) { }
getSelectedProfile(val){
this.profileValue = val;
this.isdisabled = this.profileValue ? true : false;
}
saveProfile(val){
if(this.shouldSaveProfile)
this.presentToast( this.profileValue+"set as default profile")
else this.presentToast("No default profile")
}
presentToast(val){
let toast = this.toastCtrl.create({
message: val,
duration: 3000,
position: 'top'
});
toast.present();
}
navigateTo()
{
this.shouldSaveProfile = true;
console.log("Next Clicked, should save value:", this.shouldSaveProfile);
}
}

Related

Angular View does't refresh on array push

I am very new to ionic and angular.
Anyway, I am trying to following an tutorial to create a notes app using ionic4 https://www.joshmorony.com/building-a-notepad-application-from-scratch-with-ionic/.
So, I follow the instruction. Everything is ok except that the view doesn't updated when I add new note. The code is as follow:
Note services:
import { Injectable } from '#angular/core';
import { Storage } from '#ionic/storage';
import { Note } from '../interfaces/note';
#Injectable({
providedIn: 'root'
})
export class NotesService {
public notes: Note[] = [];
public loaded: boolean = false;
constructor(private storage: Storage) {
}
load(): Promise<boolean> {
// Return a promise so that we know when this operation has completed
return new Promise((resolve) => {
// Get the notes that were saved into storage
this.storage.get('notes').then((notes) => {
// Only set this.notes to the returned value if there were values stored
if (notes != null) {
this.notes = notes;
}
// This allows us to check if the data has been loaded in or not
this.loaded = true;
resolve(true);
});
});
}
save(): void {
// Save the current array of notes to storage
this.storage.set('notes', this.notes);
}
getNote(id): Note {
// Return the note that has an id matching the id passed in
return this.notes.find(note => note.id === id);
}
createNote(title): Promise<boolean> {
return new Promise((resolve) => {
// Create a unique id that is one larger than the current largest id
let id = Math.max(...this.notes.map(note => parseInt(note.id)), 0) + 1;
this.notes.push({
id: id.toString(),
title: title,
content: ''
});
this.save();
console.log('Service Log ' + this.notes);
resolve(true);
});
}
}
The HTML code:
<ion-header>
<ion-toolbar color="primary">
<ion-title>Notes</ion-title>
<ion-buttons slot="end">
<ion-button (click)="addNote()">
<ion-icon slot="icon-only" name="clipboard"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item button detail *ngFor="let note of notesService.notes" [href]="'/notes/' + note.id" routerDirection="forward">
<ion-label>{{ note.title }}</ion-label>
</ion-item>
</ion-list>
</ion-content>
I've followed the same tutorial and got the same issue. The issue is because of something very interesting and powerful called Zones.
The idea is that you'd need to let Angular know that the array with the notes has changed, by doing something like this:
// Angular
import { Component, NgZone } from '#angular/core';
// Ionic
import { NavController, AlertController } from '#ionic/angular';
// Services
import { NotesService } from '../services/notes.service';
import { AlertOptions } from '#ionic/core';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(
private ngZone: NgZone, // Add this in the constructor
private navCtrl: NavController,
private alertCtrl: AlertController,
private notesService: NotesService,
) { }
ngOnInit() {
this.notesService.load();
}
addNote() {
const alertOptions: AlertOptions = {
header: 'New Note',
message: 'What should the title of this note be?',
inputs: [
{
type: 'text',
name: 'title'
}
],
buttons: [
{
text: 'Cancel'
},
{
text: 'Save',
handler: (data) => {
// Create the note inside a Zone so that Angular knows
// that something has changed and the view should be updated
this.ngZone.run(() => {
this.notesService.createNote(data.title);
});
}
}
]
};
this.alertCtrl
.create(alertOptions)
.then((alert) => {
alert.present();
});
}
}

How can I change the back button text and click action for a specific page in IONIC 2+?

I have found that many solutions are only answered in parts and though it might be useful to combine two solutions into one answer relating to the question asked above: "How can I change the back button text and click action for a specific page in IONIC 2+?"
This question was answered elsewhere but in many different parts meaning they only covered "changing the text" or showing how to perform a "custom click action" for the back button using various solutions. This answer is primarily to combine the two to showcase the most simple solution. This solution also includes the physical back button of devices like Android and Windows based phones. iPhones doesn't have a back button.
Each file will be displayed below in full to help junior developers see the fuller picture.
src/app/app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule, Navbar, NavController, AlertController } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { DashboardPage } from '../pages/dashboard/dashboard';
import { SitesPage } from '../pages/sites/sites';
import { NavigationProvider } from '../providers/navigation/navigation';
#NgModule({
declarations: [
MyApp,
HomePage,
DashboardPage,
SitesPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
DashboardPage,
SitesPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
NavigationProvider
]
})
export class AppModule {}
src/app/app.component.ts
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { NavigationProvider } from '../providers/navigation/navigation';
import { HomePage } from '../pages/home/home';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = HomePage;
constructor(private platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private navProvider: NavigationProvider) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
platform.registerBackButtonAction(() => {
this.navProvider.backButtonAction();
});
statusBar.styleDefault();
splashScreen.hide();
});
}
}
src/pages/dashboard/dashboard.ts
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController, NavParams, ViewController, Navbar } from 'ionic-angular';
import { SitesPage } from '../sites/sites';
import { NavigationProvider } from '../../providers/navigation/navigation';
#IonicPage()
#Component({
selector: 'page-dashboard',
templateUrl: 'dashboard.html',
})
export class DashboardPage {
#ViewChild(Navbar) navBar: Navbar;
constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public navProvider: NavigationProvider) {}
ionViewDidLoad() {
this.viewCtrl.setBackButtonText('Logout');
this.navBar.backButtonClick = () => {
this.navProvider.backButtonAction();
};
}
sites() {
this.navCtrl.push(SitesPage);
}
}
src/providers/navigation/navigation.ts
import { Injectable } from '#angular/core';
import { Platform, NavController, AlertController } from 'ionic-angular';
import { App } from "ionic-angular/index";
#Injectable()
export class NavigationProvider {
logoutAlert: any = null;
exitAppAlert: any = null;
private navCtrl: NavController;
constructor(private platform: Platform, private app: App, private alertCtrl: AlertController) {
//get the nav controller which is only ready when the platform is ready
platform.ready().then(() => {
this.navCtrl = app.getActiveNavs()[0];
});
}
//* perform the back button action
backButtonAction() {
// can we pop this page?
if(this.navCtrl.canGoBack()) {
// are we on the page that we want to trigger the logout alert?
const view = this.navCtrl.getActive();
if(view.component.name == 'DashboardPage') {
// is the logout alert still visible?
if(this.logoutAlert) {
// dismiss it instead :)
this.logoutAlert.dismiss();
this.logoutAlert = null;
} else {
// show the logout alert
this.logoutAlertAction();
}
} else {
//pop the page to perform default back action
this.navCtrl.pop();
}
} else {
// we are at the root page so the next step is to exit the app
// is the exit app alert still visible?
if(this.exitAppAlert) {
// dismiss it instead :)
this.exitAppAlert.dismiss();
this.exitAppAlert = null;
} else {
this.exitAppAlertAction();
}
}
}
//*/
//* prompt the user before logging out
logoutAlertAction() {
this.logoutAlert = this.alertCtrl.create({
title: 'Logout',
message: 'Are you sure you want to log out?',
buttons: [
{
text: 'No',
role: 'cancel',
handler: () => {
// don't do anything
}
},
{
text: 'Yes',
handler: () => {
// clear sessions or do something to log the user out before popping the page
this.navCtrl.pop();
}
}
]
});
this.logoutAlert.present();
}
//*/
//* prompt the user before exiting the application
exitAppAlertAction() {
this.exitAppAlert = this.alertCtrl.create({
title: 'Exit Application',
message: 'Are you sure you want to exit the app?',
buttons: [
{
text: 'Yes',
handler: () => {
// exit the application
this.platform.exitApp();
}
},
{
text: 'No',
role: 'cancel',
handler: () => {
// don't do anything
this.exitAppAlert = null;
}
}
]
});
this.exitAppAlert.present();
}
//*/
}

i want to retain the value of radio button when open and close the modal in Ionic2 using modalcontroller

import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams} from 'ionic-angular';
import { FormGroup, FormControl} from '#angular/forms';
import { ViewController} from 'ionic-angular';
import { ModalController } from 'ionic-angular';
import { TabsPage } from "../tabs/tabs"
#IonicPage()
#Component({
selector: 'page-dashboard',
templateUrl: 'listing.html'
})
export class ListingPage {
constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad Dashboard');
}
//modals started
filterSort() {
let modal = this.modalCtrl.create(SortModal);
modal.present();
}
}
#Component({
selector:"sort-page",
templateUrl:"filter/sort.listing.filter.html",
providers:[ListingPage]
})
export class SortModal {
relationship:string;
filtersStore:Array<string>=[];
public myForm: FormGroup;
constructor(private _filterservice:FilterModalsService,private _v:ViewController,private _sharedservice: SharedService,private listingpage:ListingPage,public navCtrl: NavController){
this.myForm = new FormGroup({
langs: new FormControl()
})
}
doSubmit() {
this.listingpage.onSearch(0,true);
this._v.dismiss();
}
reset(){
this.myForm.reset();
this._sharedservice.deleteData();
}
}
listingpage is parent component in which i open the SortModal component as modal in ionic 2 and child is SortModal but when i open the modal by defualt every element is reset and then i select one from the list and dismiss the modal but when i open the modal again all value again empty. i want retain value the element of radio which i selected before

fix the navigation with navcontroller in ionic 2

i'm trying to implement a simple ionic app with login authentification, when the user enter the credentials and hit login i sat the Root for the Nav to be the TabsPage that contains the home,contact and about pages.The problem is when the i hit the logout button in the home page it redirect the home tab(see logout function in home.ts) to the login page(set the Root to loginPage) and the three tabs stays at the bottom, i want fully redirection to the loginPage any suggestions ?
login page
after logout in home page
app.component.ts :
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { LoginPage } from '../pages/login/login';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = LoginPage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
}
}
login.ts :
import { Component } from '#angular/core';
import { NavController, AlertController, LoadingController, Loading, IonicPage } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import {TabsPage} from '../tabs/tabs';
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
loading: Loading;
registerCredentials = { email: '', password: '' };
constructor(private nav: NavController, private auth: AuthService, private alertCtrl: AlertController, private loadingCtrl: LoadingController) { }
public login() {
//this.showLoading()
this.auth.login(this.registerCredentials).subscribe(allowed => {
if (allowed) {
console.log('allowed');
this.nav.setRoot(TabsPage); //move to tabspage
} else {
this.showError("Access Denied");
console.log('denied');
}
},
error => {
this.showError(error);
});
}
showLoading() {
this.loading = this.loadingCtrl.create({
content: 'Please wait...',
dismissOnPageChange: true
});
this.loading.present();
}
showError(text) {
//this.loading.dismiss();
let alert = this.alertCtrl.create({
title: 'Fail',
subTitle: text,
buttons: ['OK']
});
alert.present(prompt);
}
}
home.ts :
import { Component } from '#angular/core';
import { NavController, IonicPage } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import {LoginPage} from '../login/login';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
username = '';
email = '';
constructor(private nav: NavController, private auth: AuthService) {
let info = this.auth.getUserInfo();
this.username = info['name'];
this.email = info['email'];
}
public logout() {
this.auth.logout().subscribe(succ => {
this.nav.setRoot(LoginPage)
});
}
}
I got around this issue by getting the navcontroller from app.
import {App, NavController, IonicPage } from 'ionic-angular';//import App
Inject the app object.
constructor(private app:App,private nav: NavController, private auth: AuthService) {//...
}
In logout function, use getRootNav().
public logout() {
this.auth.logout().subscribe(succ => {
this.app.getRootNav().setRoot(LoginPage)
});

how to get current url, on exit event InAppBrowser, Ionic2

I am trying to implement a solution where I need to get the current url on exit event of InAppBowser Ionic2.
My Code is
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {InAppBrowser} from 'ionic-native';
#Component({
selector: 'page-list',
templateUrl: 'list.html'
})
export class ListPage {
browser:any;
exit:boolean = false;
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
startPayment(){
this.browser = new InAppBrowser('https://ionic.io', '_blank','location=no,toolbar=no,hardwareback=no,EnableViewPortScale=yes,closebuttoncaption=Done');
this.browser.on("exit")
.subscribe(
(e) => {
this.checkpaymentStatus(e);
},
err => {
console.log("InAppBrowser loadstart Event Error: " + err);
});
};
checkpaymentStatus(e){
console.log(e);
console.log("in app browser exit")
this.exit = true;
}
};//
The exit event is firing properly but I am unable to get the url in event(e), it just gives Object{type:exit}.
Please tell me , how can I get the url on exit.
Thanks
just use e.url
checkpaymentStatus(e){
console.log(e.url); // you will get url here
// ... ... ...
}