get last view Ionic 4 - ionic-framework

good morning. Does anyone know the import of the NavController? I am looking at the docs of Ionic 4 docs and it says there is a method of getPrevious() however when I do:
import { NavController } from ‘#Ionic/angular’;
contructor (private navCtrl: NavController){}
private func(): void{
this.navCtrl.getPrevious();
}
I get an error saying property getPrevious does not exist on type NavController however in the docs it says that it exists. anyone aware of the proper import since it isn't documented?
previously you were able to do this with Ionic 2-3 but not Ionic 4.
side note* method last() doesn't exist either.

What do you want to do? If you want to go back, than you could use the ion-back-button.
<ion-buttons slot="start">
<ion-back-button color="light"></ion-back-button>
</ion-buttons>
Also you can use the NavController like this to get forward:
constructor(private navCtrl: NavController) { }
GotoImpressum() {
this.navCtrl.navigateForward('impressum');
}

Related

Ionic 4 Scroll Position in Service/Guard

I am trying to implement a feature similar to whats available in Facebook i.e. if you have scrolled the news feed, pressing hardware back button takes you to the top of the list.
For this I think believe canDeactivate of Router Guards would be the proper ways.
But I am unable to find a way to check if the page has been scrolled or not.
I have tried window.pageYOffset but this always returns 0, accessing ViewChild within a Guard always returns null.
Can anyone please guide how to achieve this?
There are two approaches for this that should help you.
First, starting with Ionic 4, you can register you back button handler using the Platform features:
https://www.freakyjolly.com/ionic-4-overridden-back-press-event-and-show-exit-confirm-on-application-close/
this.platform.backButton.subscribeWithPriority(999990, () => {
//alert("back pressed");
});
Secondly, you can use more features of Ionic 4 called scrollEvents.
I have explained how to use this feature in other answers:
How to detect if ion-content has a scrollbar?
How to detect scroll reached end in ion-content component of Ionic 4?
ionic 4 - scroll to an x,y coordinate on my webView using typeScript
Hopefully that will get you moving in the right direction.
I think that last answer should solve most of your issue, so something like this:
Freaky Jolly has a tutorial explaining how to scroll to an X/Y coord.
First, you need scrollEvents on the ion-content:
<ion-header>
<ion-toolbar>
<ion-title>
Ion Content Scroll
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content [scrollEvents]="true">
<!-- your content in here -->
</ion-content>
In the code you need to use a #ViewChild to get a code reference to the ion-content then you can use its ScrollToPoint() api:
import { Component, ViewChild } from '#angular/core';
import { Platform, IonContent } from '#ionic/angular';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
// This property will save the callback which we can unsubscribe when we leave this view
public unsubscribeBackEvent: any;
#ViewChild(IonContent) content: IonContent;
constructor(
private platform: Platform
) { }
//Called when view is loaded as ionViewDidLoad() removed from Ionic v4
ngOnInit(){
this.initializeBackButtonCustomHandler();
}
//Called when view is left
ionViewWillLeave() {
// Unregister the custom back button action for this page
this.unsubscribeBackEvent && this.unsubscribeBackEvent();
}
initializeBackButtonCustomHandler(): void {
this.unsubscribeBackEvent = this.platform.backButton.subscribeWithPriority(999999, () => {
this.content.scrollToPoint(0,0,1500);
});
/* here priority 101 will be greater then 100
if we have registerBackButtonAction in app.component.ts */
}
}

Ionic 3- Hide navbar and tabs on scroll down, and show on scroll up

I'm working on Ionic App, I want to hide navbar and tabs on scroll down and show them on scroll up.
Anyone know how to do this? Please help.
Thanks in advance.
a very naive implementation would be:
add a var that will be your boolean flag for state (shown/hidden)
add change detector ref into your component (as you will need to cdr
change of this boolean to propagate UI)
bind your header/footer via *ngIf directive
Something like this:
import { Component, ChangeDetectorRef } from '#angular/core';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage2 {
headerVisible: boolean = false;
constructor(
public cdr: ChangeDetectorRef
) {
}
scrollState(event) {
if (event.directionY == "up") {
this.headerVisible = false;
} else {
this.headerVisible = true;
}
this.cdr.detectChanges();
}
}
And in your template:
<ion-header *ngIf="headerVisible">
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
But most probably instead of *ngIf you would want to alter header's/footer's height so that your overall template dealt better with margins.
Also please note that ideally you don't want scroll event to "spam" so you need to implement proper way you capture the state (up or down) without it (debounce / throttle it)

Share FireStoreCollection to serveral views

im having an ionic project with a firestore backend using 'angularfire2/firestore'.
To share a collection between views i created a firebaseservice provider:
interface if_friend {
name: string;
email: string;
id?: any;
}
friendsCollection: AngularFirestoreCollection<if_friend>;
friends$: Observable<if_friend[]>;
constructor(public afStore: AngularFirestore) {
console.log('Hello FirebaseServiceProvider Provider');
this.friendsCollection = afStore.collection('/testmail#googlemail.com/Friends/friends/');
this.friends$ = this.friendsCollection.valueChanges();
}
getFriends(){
return this.friends$;
}
On the constructor of the views im getting the Obserable like this:
public friends$: Observable<if_friend[]>;
constructor(public navCtrl: NavController, public firebaseService: FirebaseServiceProvider) {
this.friends$ = this.firebaseService.getFriends();
}
and using it in the html file with the async pipe:
<ion-list>
<ion-item *ngFor="let friend of friends$ | async">
This works well for the first view im entering.
The problem im facing is, that the data will not appear on the secound view (im doing the same there).
I think i have to unsubscribe from the observable, if im leaving the first view or maybe i need to rewrite the data into a separte array.
Can anyone please tell me how to share the observable correctly between two views?
Thanks and best regards!
i needed to return the collection from the service and use the valueChanges in the views.
Seems like the async pipe now works correctly.
Best regards

Go back to the previous state

I am trying various solutions from Google but all of them seems to be for Ionic 1 and other versions of Ionic and Angular.
HTML
<button class="edit" (click)="goBackToEnhancementPage();">Edit</button>
On button click I want to goto to the previous state in the history
TypeScript
This is the current state
export class BookingConfirmationPage {
//Some properties
constructor(public navCtrl: NavController, public navParams: NavParams ) {
//Some codes
}
goBackToEnhancementPage(){
canGoBack();
}
}
Previous State
export class BookingEnhancementPage {
//Some code
constructor(public navCtrl: NavController, public navParams: NavParams, public loadingCtrl: LoadingController, private formBuilder: FormBuilder ) {
//This is previous state
}
}
This doesn't work. Please advise what am I doing wrong?
I'm guessing from your question you are trying to use navController to go back to your previous state, aka "back" function.
The way ionic navigation works is like a stack, new pages will be pushed to the top of the stack via "push" via pages will be removed from the top of the stack via "pop"
To go back to your previous state, u can use :
this.navCtrl.pop();
But before that make sure you have push your previous page into navController or you have setRoot your "BookingConfirmationPage" page.
You might want to read up on : https://ionicframework.com/docs/v2/api/navigation/NavController/
If you want your previous details in BookingEnhancementPage to be filled with your user's previously entered data, you might want to use a combination of localstorage and onPageBeforeEnter/onPageWillEnter to populate the fields.

How to redirect to an external URL in Angular2?

What is the method for redirecting the user to a completely external URL in Angular 2. For example, if I need to redirect the user to an OAuth2 server in order to authenticate, how would I do that?
Location.go(), Router.navigate(), and Router.navigateByUrl() are fine for sending the user to another section (route) within the Angular 2 app, but I can't see how they could be used to redirect to an external site?
You can use this-> window.location.href = '...';
This would change the page to whatever you want..
An Angular approach to the methods previously described is to import DOCUMENT from #angular/common (or #angular/platform-browser in Angular
< 4) and use
document.location.href = 'https://stackoverflow.com';
inside a function.
some-page.component.ts
import { DOCUMENT } from '#angular/common';
...
constructor(#Inject(DOCUMENT) private document: Document) { }
goToUrl(): void {
this.document.location.href = 'https://stackoverflow.com';
}
some-page.component.html
<button type="button" (click)="goToUrl()">Click me!</button>
Check out the platformBrowser repo for more info.
The solution, as Dennis Smolek said, is dead simple. Set window.location.href to the URL you want to switch to and it just works.
For example, if you had this method in your component's class file (controller):
goCNN() {
window.location.href='http://www.cnn.com/';
}
Then you could call it quite simply with the appropriate (click) call on a button (or whatever) in your template:
<button (click)="goCNN()">Go to CNN</button>
I think you need à target="_blank", so then you can use window.open :
gotoGoogle() : void {
window.open("https://www.google.com", "_blank");
}
If you've been using the OnDestry lifecycle hook, you might be interested in using something like this before calling window.location.href=...
this.router.ngOnDestroy();
window.location.href = 'http://www.cnn.com/';
that will trigger the OnDestry callback in your component that you might like.
Ohh, and also:
import { Router } from '#angular/router';
is where you find the router.
---EDIT---
Sadly, I might have been wrong in the example above. At least it's not working as exepected in my production code right now - so, until I have time to investigate further, I solve it like this (since my app really need the hook when possible)
this.router.navigate(["/"]).then(result=>{window.location.href = 'http://www.cnn.com/';});
Basically routing to any (dummy) route to force the hook, and then navigate as requested.
in newer versions of Angular with window as an any
(window as any).open(someUrl, "_blank");
There are 2 options:
if you want to redirect in same window/tab
gotoExternalDomain(){
window.location.href='http://google.com/'
}
if you want to redirect in new tab
gotoExternalDomain(){
(window as any).open("http://google.com/", "_blank");
}
After ripping my head off, the solution is just to add http:// to href.
Go somewhere
I used window.location.href='http://external-url';
For me the the redirects worked in Chrome, but didn't work in Firefox.
The following code resolved my problem:
window.location.assign('http://external-url');
I did it using Angular 2 Location since I didn't want to manipulate the global window object myself.
https://angular.io/docs/ts/latest/api/common/index/Location-class.html#!#prepareExternalUrl-anchor
It can be done like this:
import {Component} from '#angular/core';
import {Location} from '#angular/common';
#Component({selector: 'app-component'})
class AppCmp {
constructor(location: Location) {
location.go('/foo');
}
}
You can redirect with multiple ways:
like
window.location.href = 'redirect_url';
another way Angular document:
import document from angular and the document must be inject as well as bellow otherwise you will get error
import { DOCUMENT } from '#angular/common';
export class AppComponent {
constructor(
#Inject(DOCUMENT) private document: Document
) {}
this.document.location.href = 'redirect_url';
}
None of the above solutions worked for me, I just added
window.location.href = "www.google.com"
event.preventDefault();
This worked for me.
Or try using
window.location.replace("www.google.com");
To use #Inject, you must import it. I didn't see this in any of the answers.
TS file:
import { Component, Inject } from '#angular/core';
import { DOCUMENT } from '#angular/common';
#Component({
selector: 'app-my-comp.page',
templateUrl: './my-comp.page.component.html',
styleUrls: ['./my-comp.page.component.scss']
})
export class MyCompPageComponent {
constructor(
#Inject(DOCUMENT) private document: Document
) { }
goToUrl(): void {
this.document.location.href = 'https://google.com/';
}
}
HTML file:
<button type="button" (click)="goToUrl()">Google</button>
In your component.ts
import { Component } from '#angular/core';
#Component({
...
})
export class AppComponent {
...
goToSpecificUrl(url): void {
window.location.href=url;
}
gotoGoogle() : void {
window.location.href='https://www.google.com';
}
}
In your component.html
<button type="button" (click)="goToSpecificUrl('http://stackoverflow.com/')">Open URL</button>
<button type="button" (click)="gotoGoogle()">Open Google</button>
<li *ngFor="item of itemList" (click)="goToSpecificUrl(item.link)"> // (click) don't enable pointer when we hover so we should enable it by using css like: **cursor: pointer;**
Just simple as this
window.location.href='http://www.google.com/';