简体   繁体   中英

Getting focus on buttons p-toast primeng modal

Here is the modal that gets displayed when a user selects something to delete.

How can the focus be set on the buttons and not stay at the underlying content below the modal?

<p-toast position="center" key="modal" (onClose)="onDeleteReject()" [modal]="true" [baseZIndex]="5000">
  <ng-template let-message pTemplate="message">
    <div style="text-align: center">
      <i class="pi pi-exclamation-triangle" style="font-size: 3em"></i>
      <h3>{{message.summary}}</h3>
      <p>{{message.detail}}</p>
    </div>
    <div class="ui-g ui-fluid" focus="true">
      <div class="ui-g-6">
        <button type="text" pButton (click)="onDeleteConfirm()" label="Oui" class="ui-button-success"></button>
      </div>
      <div class="ui-g-6">
        <button type="text" pButton (click)="onDeleteReject()" label="Non" class="ui-button-secondary"></button>
      </div>
    </div>
  </ng-template>
</p-toast>

Using autofocus seems to work but only on the first load of the modal.

<button type="button" pButton (click)="onDeleteConfirm()" label="Oui" 
         class="ui-button-success" autofocus>
</button>

https://www.primefaces.org/primeng/#/toast

angular directive work perfectly here ,in short just get a reference (el) of the element (confirm button) and run focus method when angular lifecycle hook ngAfterViewInit .

def-focus.directive

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

@Directive({
  selector: '[defFocus]'
})
export class DefFocusDirective implements AfterViewInit {

  constructor(private el: ElementRef) { }

  ngAfterViewInit(){
    console.log('rendered 😁');
    console.log(this.el.nativeElement.focus())
  }

}

template

<div class="ui-g-6">
   <button type="button" pButton (click)="onConfirm()" 
           label="Yes" class="ui-button-success" defFocus >
   </button>
 </div>

ngAfterViewInit() { ... }

Called after ngAfterContentInit when the component's views and child views / the view that a directive is in has been initialized.

stackblitz demo 🚀🚀

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM