繁体   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