Aleksandr Neizvestnyi
Aleksandr Neizvestnyi

Reputation: 578

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.

Upvotes: 6

Views: 3075

Answers (3)

Carlos Garcia
Carlos Garcia

Reputation: 113

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>

Upvotes: 2

Aleksandr Neizvestnyi
Aleksandr Neizvestnyi

Reputation: 578

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>

Upvotes: 3

Yash Shah
Yash Shah

Reputation: 1

You can set editor style display:none untill your page load. Once it is loaded enable it set display:inline; using setTimeout() if you are using javascript.

Upvotes: 0

Related Questions