簡體   English   中英

角度4設置焦點在模態的字段中

[英]angular 4 set focus in a field of a modal

在我的角度4項目中,我需要將一些字段集中在bootstrap-modal中

這是模式:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
    <i class="material-icons">clear</i>
    </button>
    <h4 class="modal-title">{{'checkpoint.table.dialog.title' | translate }}</h4>
   </div>
   <form #modelForm="ngForm">
  <div class="modal-body">
    <div class="row">
        <div class="col-md-8">
            <div class="form-group label-floating">

                <label class="control-label">{{'checkpoint.table.dialog.labels.name' | translate }}
                <span class="star">*</span>
                </label>
                <input class="form-control" id="name" name="name" required [(ngModel)]="checkpoint.name" #focus />

            </div>
        </div>
    </div>

我用普通按鈕打開對話框

<button type="button" class="btn btn-info btn-lg" 
data-toggle="modal" data-target="#myModal">Open Modal</button>

我嘗試了一些解決方案,如:

@ViewChild('focus') inputElement: ElementRef;

當我打開模態時按鈕:

this.inputElement.nativeElement.focus();

要么:

$('#myModal').on('shown.bs.modal', function () {
      $('#focus').focus();

但在第一種情況下,inputElement是未定義的,在第二種情況下,沒有任何事情發生

我為此編寫了一個指令,當模態打開時,輸入字段會自動聚焦。

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

@Directive({
    selector: '[focus]'
})
export class FocusDirective implements AfterViewInit {
    @Input() focus: boolean;

    constructor(private element: ElementRef) {}

    ngAfterViewInit() {
        if (this.focus) {
            this.element.nativeElement.focus();
        }
    }
}

在html中使用它:

<input type="text"
       (keyup)="search($event)"
       focus="true"
>

您將需要使用setTimeOut來鍛煉..
雖然它不應該是未定義的,你的@ViewChild('focus')的代碼看起來還不錯,但如果它不起作用,那么嘗試將名稱從焦點更改為其他東西......因為焦點也是關鍵字......

另外我建議不要混合使用Jquery和Angular ......不是很好的做法。

 setTimeout(() => {
        this.inputElement.nativeElement.focus();
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM