How to hide header on scroll in ionic 4? - ionic-framework

I wanted to know how I can hide a header in Ionic 4 by scrolling down the page, and re-show it when scrolling up.
I found many solutions on how to do that, but they all turned out to not working or being out-of-date.
So I collected all piece of information I could find to provide this answer.

Thanks to this video I got it to work.
First of all call ionic g directive directives/hide-header. You can of course replace directive/hide-header with your own path and name.
hide-header.directive.ts
import { Directive, HostListener, Input, OnInit, Renderer2 } from '#angular/core';
import { DomController } from '#ionic/angular';
#Directive({
selector: '[appHideHeader]'
})
export class HideHeaderDirective implements OnInit {
#Input('header') header: any;
private lastY = 0;
constructor(
private renderer: Renderer2,
private domCtrl: DomController
) { }
ngOnInit(): void {
this.header = this.header.el;
this.domCtrl.write(() => {
this.renderer.setStyle(this.header, 'transition', 'margin-top 700ms');
});
}
#HostListener('ionScroll', ['$event']) onContentScroll($event: any) {
if ($event.detail.scrollTop > this.lastY) {
this.domCtrl.write(() => {
this.renderer.setStyle(this.header, 'margin-top', `-${ this.header.clientHeight }px`);
});
} else {
this.domCtrl.write(() => {
this.renderer.setStyle(this.header, 'margin-top', '0');
});
}
this.lastY = $event.detail.scrollTop;
}
}
After that, in your template:
<ion-header #header>
<ion-toolbar><ion-title>Test</ion-title></ion-toolbar>
</ion-header>
<ion-content scrollEvents="true" appHideHeader [header]="header">
</ion-content>
Take care of the scrollEvents, appHideHeader and the [header] attributes! The last one takes the header element as argument, in this case #header.
Most of the code is the same as shown in the video. I changed the host-property from the #Directive and used the more up-to-date HostListener.
If you want to use the directive in more than one directive, you need to create a SharedModule.
To do so, create the module with ng g module shared. After that, add the HideHeaderDirective to the declarations and the exports array.
shared.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { HideHeaderDirective } from './directives/hide-header.directive';
#NgModule({
declarations: [HideHeaderDirective],
exports: [HideHeaderDirective],
imports: [
CommonModule
]
})
export class SharedModule {}
Now add the shared module to all the modules you want to use the directive in.
Note: You cannot import the directive in app.module.ts and use it in a submodule! You have to import the shared module in every direct module you want to use the directive in.
My current versions of node, npm and ionic:

For this you can just place the ion-header before the ion-content. this is the simple answer for that.

Related

How do you setup angular-bootstrap-toggle on an Angular 9 app?

I'm learning Angular 9 and have gone through the Tour of Heroes app and tutorial. I've used this tutorial as a base to add new features such as CRUD operations on a remote resource and I have added #ng-bootstrap/ng-bootstrap to the projects but I cannot get angular-bootstrap-toggle to work.
The instructions on Bootstrap Toggle don't match what I have learned so far and I can't find a solution anywhere.
For example, I don't know how this command angular.module('myApp', ['ui.toggle']); fits in with Angular 9 and the tutorial I have used.
How can I get the system to call onChange() when I click the toggle?
angular.json
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"node_modules/bootstrap4-toggle/css/bootstrap4-toggle.min.css",
"src/styles.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.bundle.js",
"node_modules/bootstrap4-toggle/js/bootstrap4-toggle.min.js"
]
navigation-bar.component.html This displays correctly and toggles as expected
<input id="local-browse" (change)="onChange()" type="checkbox" checked="" data-toggle="toggle" data-on="Local" data-off="Remote" data-onstyle="success" data-offstyle="danger" data-size="sm">
navigation-bar.component.ts If I put in a standard checkbox the onChange() does work as expected but not with angular-bootstrap-toggle
import { Component, OnInit } from '#angular/core';
declare var $: any;
#Component({
selector: 'app-navigation-bar',
templateUrl: './navigation-bar.component.html',
styleUrls: ['./navigation-bar.component.css'],
})
export class NavigationBarComponent implements OnInit {
localUrl = 'http://192.168.253.53';
remoteUrl = 'https://remoteaddress.com';
local = true;
constructor() {}
ngOnInit(): void {
$(document).ready(() => {
console.log('The document ready for jQuery!');
});
}
onChange() {
if (this.local === true) {
this.local = false;
} else {
this.local = true;
}
}
}
I dont think it is compatible with Angular 2+ (or at least angular 9).
You may like to use ng-toggle from https://www.npmjs.com/package/#nth-cloud/ng-toggle
Which is tested on Angular 9.
More information about installation in https://nth-cloud.github.io/ng-toggle/#/home

Detect a click outside of an element

There is some components in Ionic that do not provide an event that is emitted when focus is lost.
For example ion-input provides ionBlur. On the other hand there is other elements like ion-content where I need to detect an outside click, but without knowing which event to use.
Is there a way to achieve that without being limited to the proposed events in the documentation?
I found this article that shows a way to use a custom directive to detect an outside click:
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '#angular/core';
#Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
constructor(private _elementRef : ElementRef) {
}
#Output()
public clickOutside = new EventEmitter();
#HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this.clickOutside.emit(null);
}
}
}
The directive can then be used this way, after declaring it in the concerned module:
<!-- HTML Template -->
<ion-content (clickOutside)="handleOutsideClick()"><!-- ... --></ion-content>
<!-- Typescript code -->
handleOutsideClick() {
//Handle My outside Click
}
Yeah, It's been 7 months since asked.
Stucked with the same issue; this solved the issue
TS
#ViewChild('content') content: ElementRef
#HostListener('document:click', ['$event'])
andClickEvent(event) {
if (!this.content.nativeElement.contains(event.target)) {
if (!this.navCtrl.isTransitioning() && this.navCtrl.getActive()) {
this.close()
}
}
}
HTML
<ion-content #content>

I'm trying to declare a custom component to use in two different pages (of my ionic app) but getting an error

I'm trying to use a custom component called UserCardComponent in two different pages in my ionic v3 app.
I followed this answer (the one with 26 votes) which says to declare custom components in "a specific page's module.ts file". Custom component in ionic v3
So I firstly declared the component in my HomePageModule and was able to use it fine within the home.html.
home.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';
import { UserCardComponent } from '../../components/user-card/user-card';
#NgModule({
declarations: [
HomePage,
UserCardComponent
],
imports: [
IonicPageModule.forChild(HomePage)
],
})
export class HomePageModule {}
I then tried to declare it (in the same way) in ContactsPageModule to use in contacts.html however I get the following error:
Type UserCardComponent is part of the declarations of 2 modules: HomePageModule and ContactsPageModule!
Please consider moving UserCardComponent to a higher module that imports HomePageModule and ContactsPageModule.
You can also create a new NgModule that exports and includes UserCardComponent then import that NgModule in HomePageModule and ContactsPageModule
When I try to just declare the UserCardComponent in the app.module.ts file I get a Template parse error and the custom component won't work in any pages.
Can you advise me on what to do? The error says to move the "UserCardComponent to a higher module that imports HomePageModule and ContactsPageModule. "
Can you tell me how I would do this? I'm new to ionic. Thanks
If you declare the UserCardComponent in the HomePageModule, you only need to import the HomePageModule in the ContactsPageModule but it introduces dirty dependency between theses modules.
A better way is to declare UserCardComponent in a specific module UserCardModule and then to import this specific module in HomePageModule and in ContactsPageModule.
user-card.module.ts
import { NgModule } from '#angular/core';
import { UserCardComponent } from './user-card';
#NgModule({
declarations: [
UserCardComponent
]
})
export class UserCardModule {}
home.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';
import { UserCardModule } from '../../components/user-card/user-card.module';
#NgModule({
declarations: [
HomePage
],
imports: [
IonicPageModule.forChild(HomePage),
UserCardModule
],
})
export class HomePageModule {}

Ionic2 - Alternate way to route without using injected component?

I am building a mobile app and I'd like the user to have the ability to set their starting page via a settings-page. The idea is that the user can select a page from a list of options, the setting gets stored to local-storage and later, when the user logs back in, the user is automatically taken to that page first.
I have a page-service which contains a mapping of Id's to page-components. This is what I use to find the page I want to use when I read in my user's saved start-page data.
My issue is that I have developed a cyclic-dependency that I don't think I can break without finding a way to route in Ionic2 that doesn't involve using the injected component. As far as I can tell, the only way routing is achieved in Ionic2 is with the NavController.push(component) or Nav.setRoot(component).
PageService.ts
import {Injectable} from "#angular/core";
import {HomePage} from "../pages/home/home";
import {SettingsPage} from "../pages/settings/settings";
import {CartPage} from "../pages/cart/cart";
#Injectable()
export class PageService {
public pages = [
{
id: "HOME",
component: HomePage
}, {
id: "SETTINGS",
component: SettingsPage
}, {
id: "CART",
component: CartPage
}
];
constructor() {
}
getPageById(id: string) {
return this.pages.find(page => (page.id === id));
}
}
settings.ts:
My SettingsPage component has the PageService injected so that it can get access to get the list of pages. This is where my cyclical dependency occurs. The SettingsPage is injecting PageService which has a reference to SettingsPage in it.
import {Component} from "#angular/core";
import {PageService} from "../../providers/page-service";
import {UserService} from "../../providers/user-service";
#Component({
selector: "page-settings",
templateUrl: "settings.html",
})
export class SettingsPage {
startPages = [];
constructor(private pageService: PageService, private userService: UserService) {
this.startPages = this.pageService.getStartPages();
}
}
settings.html:
Just a simple list with a card to output the selection.
<ion-content padding>
<ion-list>
<ion-card padding>
<ion-card-title>Starting Page</ion-card-title>
<ion-item>
<ion-select [(ngModel)]="userService.activeUser.startPage">
<ion-option *ngFor="let page of startPages" value="{{page.id}}">
{{page.id}}
</ion-option>
</ion-select>
</ion-item>
</ion-card>
</ion-list>
</ion-content>
...and finally, when the app starts up and I want to automatically go to my start page I execute the following:
const startPage = this.pageService.getPageById(this.userService.activeUser.startPage);
this.nav.setRoot(startPage.component);
Updated answer
Use forward ref in the SettingsPage constructor..
constructor(#Inject(forwardRef(() => PageService)) private pageService: PageService) {
this.startPages = this.pageService.getStartPages();
}
Old Answer - not appropriate because angular should be handling the instantiation of services through injection. "new"ing is a bad idea (but it did work).
I changed how the PageService was loaded in the SettingsPage and the cyclical dependency was resolved. I moved the PageService code out of the constructor and put it into the ngAfterViewInit() function. Now the PageService is only instantiated when the view is loaded.
ngAfterViewInit(){
this.pageService = new PageService();
this.startPages = this.pageService.getStartPages();
}

Ionic SqlStorage is not defined

I'm trying to use SqlStorage in an ionic app. I'm getting the error in the title. I'm guessing I need to include SqlStorage but I'm not sure where. My code looks a lot like what's in the docs http://ionicframework.com/docs/v2/api/platform/storage/SqlStorage/ . How do you include SqlStorage?
var prefrences = {
foo: bar
}
let storage = new Storage(SqlStorage);
storage.set('storedPreferences', preferences);
Add SqlStorage to your list of 'include' packages via import statement. i.e
import {SqlStorage} from 'ionic-angular';
For example
import {SqlStorage,...} from 'ionic-angular';
#Page({
templateUrl: 'path/to/template'
})
export class MyPage {
constructor(){
let storage = new Storage(SqlStorage);
...
}
...
}