Getting focus on buttons p-toast primeng modal

半城伤御伤魂 提交于 2019-12-11 06:33:37

问题


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


回答1:


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 🚀🚀



来源:https://stackoverflow.com/questions/57436328/getting-focus-on-buttons-p-toast-primeng-modal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!