Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrimeNG editor component auto focus on page loading

I am using PrimeNG UI Library's Editor component. Currently, version is 6.1.2. The problem appears when the page is loaded, and the Editor has some content, the page automatically scrolls to the editor and focus on it. How to disable this autofocus? I've tried to use simple window.scroll(0,0), but it looks strange when on page loading it scrolls down and then up.

Probably the issue with quill text editor, which is used in PrimeNG. Anyway, any workaround here? Thank you.

like image 416
Aleksandr Neizvestnyi Avatar asked Aug 29 '18 10:08

Aleksandr Neizvestnyi


2 Answers

We ended up with the following solution: Had to add Directive which use method NgOnChanges (because issue happens not only on page load, also when content is changed programmatically). So, on change action, display style changes to 'none', then after timeout show element.

Directive:

import { Directive, Input, OnChanges, SimpleChange, ElementRef } from "@angular/core";

@Directive({
    selector: '[p-editor-model]'
})
export class PeAutoscrollFixDirective implements OnChanges {
    @Input("p-editor-model") content: string;

    ngOnChanges(changes: { [property: string]: SimpleChange }) {
        let change = changes["content"];
        let elemPosition = this.element.nativeElement.getBoundingClientRect().top + document.body.scrollTop;
        let clientHeight = document.documentElement.clientHeight;

        if (change.isFirstChange() || elemPosition > clientHeight)
        {
            this.element.nativeElement.style.display = 'none';
            setTimeout(() => {
                this.element.nativeElement.style.display = '';
            });
        }
    }

    constructor(private element: ElementRef) {
    }
}

Need to add this directive to Module as declarations and exports.

And using this directive looks like:

<p-editor [p-editor-model]="model" [(ngModel)]="model"></p-editor>
like image 199
Aleksandr Neizvestnyi Avatar answered Oct 21 '22 08:10

Aleksandr Neizvestnyi


To anyone who finds it useful: it can also be done by using a public variable to control the readonly attribute. Initialize the variable as true, and then change it to false in the onAfterViewInit.

component.ts:

import { OnInit, AfterViewInit } from '@angular/core';

export class myComponent implements OnInit, AfterViewInit {
    public tempReadOnly: boolean = true;

    ngAfterViewInit() {
        this.tempReadOnly = false;
    }
}

component.html:

<p-editor [readonly]="tempReadOnly" [(ngModel)]="model"></p-editor>

You can even use an additional readonly variable if necessary and use it like this:

<p-editor [readonly]="isReadOnly || tempReadOnly" [(ngModel)]="model"></p-editor>
like image 27
Carlos Garcia Avatar answered Oct 21 '22 08:10

Carlos Garcia