Refresh feature in Angular2/TypescriptRefresh functionality using Angular2/

I am currently working on a mobile project using Angular2, Typescript, and PhoneGap, and I am trying to implement Pull to Refresh functionality without using Onsenui, Ionic, or jQuery due to project limitations.

Being a new Angular developer (specifically a Junior Dev), I have struggled to find examples in Angular2/Typescript that do not rely on the frameworks mentioned above. Most of the available libraries are for Angular1 and no longer maintained. You can check them out here and here.

My query is: Are there any Angular2 examples I can refer to for solving this problem, or are there alternative solutions? If not, would it be worthwhile to become proficient in Angular1 in order to adapt one of these abandoned projects to Angular2?

Answer №1

If you're new to angular 1, it's worth familiarizing yourself with the basics before diving into angular2. As angular2 is still in its early stages, you may need to implement some features that are not yet available. For now, I've put together a simple implementation of the initial library you provided.

@Component({
    selector: 'ptr-container',
    styles: [`
        :host {
            display: block;
            max-height: 50px;
            overflow: auto;
        }
    `],
    template: `
        <section [hidden]="!inProgress">
            refresh in progress ... (change it by your own loader)
        </section>
        <ng-content></ng-content>
    `
})
export class PullToRefreshComponent {
    private lastScrollTop:number = 0;
    private isAtTop:boolean = false;
    private element:any;

    @Input('refresh') inProgress:boolean = false;
    @Output() onPull:EventEmitter<any> = new EventEmitter<any>();

    constructor(el:ElementRef) {
        this.element = el.nativeElement;
    }

    private get scrollTop() { return this.element.scrollTop || 0; }

    @HostListener('scroll')
    @HostListener('touchmove')
    onScroll() {
        if(this.scrollTop <= 0 && this.lastScrollTop <= 0) {
            if(this.isAtTop) this.onPull.emit(true);
            else this.isAtTop = true;
        }
        this.lastScrollTop = this.scrollTop;
    }

}

Here's a simple example of how to use it

@Component({
    selector: 'app',
    template: `
        <ptr-container (onPull)="onPull()" [refresh]="isInProgress"></ptr-container>
    `
})
export class AppComponent {

    isInProgress:boolean = false;

    onPull() {
        this.isInProgress = true;
    }

}

I haven't thoroughly tested the basic library, but it should work. You may need to debounce the onScroll method to prevent excessive event triggering.

Hope this information proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

You need to provide 1 type argument(s) for the Generic type ModuleWithProviders<T> in Angular 10 Swagger Codegen

Currently, I am generating Codegen proxies using . Upon implementing this in Angular 10, I encountered the following error. How can this issue be resolved? The error message reads: 'Generic type 'ModuleWithProviders' requires 1 type argume ...

Generate an Observable<boolean> from a service function once two subscriptions have successfully completed

I am working on setting up a simple method to compare the current username with a profile's username in an Angular service. It is necessary for the profile username and user's username to be resolved before they can be compared. How can I create ...

Ignoring setTimeout() function within forEach() in Angular leads to issues

I am currently working on the frontend development of a Web Application using Angular. My task involves saving data from an array into a database by making repeated API calls until all the array data is processed. I implemented the use of setTimeout() in ...

An error occurred in the ngrx store with Angular during production build: TypeError - Unable to access property 'release' of undefined

After deploying my application and running it, I encountered an issue that seems to be happening only during production build at runtime. At this point, I am uncertain whether this is a bug or if there is a mistake in my code. The error "TypeError: Cannot ...

Exploring TypeScript Compiler Options for ensuring code compliance beyond the confines of strict mode

Our goal is to set up TypeScript Compiler (TSC) with a command line option that can identify errors when developers declare class fields using implicit type expressions instead of explicit ones as illustrated below. class Appliance { //Desired coding ...

Issue encountered: Unable to access the property 'loadChildren' as it is undefined, while attempting to configure the path

How can I conditionally load the route path? I've attempted the code below, but it's throwing an error. Can someone guide me on how to accomplish this task? [ng] ERROR in Cannot read property 'loadChildren' of undefined [ng] i 「w ...

Error encountered in Jest mockImplementation: Incompatible types - 'string[]' cannot be assigned to 'Cat[]' type

Recently, I've been writing a unit test for my API using Jest and leveraging some boilerplate code. However, I hit a snag when an error popped up that left me scratching my head. Here is the snippet of code that's causing trouble: describe(' ...

A standard set of code used to manage various HTTP methods such as retrieving data, updating data, adding new

Previously in angularjs or angular-1, there was a shared code snippet to manage various http methods like GET, PUT, POST, DELETE, // Used for GET, PUT, POST, DELETE requests sharedService.process(method, url, data, headers).then(function(result){ / ...

Unable to send a function as props to a child component in TypeScript

Within my application, I have a parent component that holds a state and a setState function. This state and function are then passed down to a child component in order to retrieve values (such as input field data). When the function is triggered in the chi ...

Issues arise during the deployment of Angular7 production build when passing through the Bitbucket package manager

I am working on a project to create a system that allows Angular components to be reused across multiple applications via BitBucket. Currently, I have the following setup: BitBucket Repo A - This repository stores the node module. The module is develope ...

How should one handle the potential risks presented by literal types?

As I was translating a large JavaScript project into TypeScript, something caught my attention. Consider a module that looks like this: WinConstants.ts export = { "no_win":0, "win":1, "big_win":2, "mega_win":3 } I wanted to make it truly constan ...

How can I call a global function in Angular 8?

Currently implementing Angular 8, my objective is to utilize downloaded SVG icons through a .js library. To achieve this, I have made the necessary additions to my .angular.json file: "scripts": [ "node_modules/csspatternlibrary3/js/site ...

Encountered difficulties in deploying functions on Firebase Cloud Functions

While developing the Firebase Cloud Functions, I organized the files based on each function. Unfortunately, numerous errors occurred during deployment. Error [debug] [2022-07-19T14:36:17.677Z] <<< [apiv2][body] GET https://us.gcr.io/v2/xxxxxx/gcf ...

An effective way to define the type of a string property in a React component using Typescript

One of the challenges I'm facing is related to a React component that acts as an abstraction for text fields. <TextField label="Enter your user name" dataSource={vm} propertyName="username" disabled={vm.isSaving} /> In this set ...

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...

Tips for effectively setting up your Angular project for success

Recently, I started working on a simple project: https://stackblitz.com/edit/angular-rktmgc-ktjk3n?file=index.html The main code resides in: /index.html <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <div ...

Implementing TypeScript in React FlatList

While TypeScript is a powerful tool, sometimes it feels like I'm working more for TypeScript than it's working for me at the moment. I'm currently using a FlatList to display restaurant results in a Carousel. const renderRestaurantRows = ( ...

analyzing properties through unit testing

Currently in the process of writing unit tests for computed properties. I have a file called fileOne.ts : export const fileOne = () => { const fx1 = computed ( () => { ... } ); const fx2 = computed ( () => { ... } ); const fx3 = comp ...

Tips on how to retrieve a stubbed Observable<void> in RxJS

Currently, I am attempting to stub an API and would like to retrieve a stubbed response from my Service. The method in my service appears as follows: public addItem(item): Observable<void> { this.listOfItems.push(item); return of(); } As f ...

Tips for fixing the HTTP error 431 in Next.js with Next-Auth

I am encountering an issue with rendering a photo in jwt via token. Tools utilized: nextjs, typescript, next-auth, keycloak, LDAP The image is retrieved from LDAP and passed to the keycloak user. My application is responsible for storing the jwt token po ...