简体   繁体   English

角度4设置焦点在模态的字段中

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

In my angular 4 project I need to focus some field inside a bootstrap-modal 在我的角度4项目中,我需要将一些字段集中在bootstrap-modal中

This is the 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>

I open the dialog with a normal button 我用普通按钮打开对话框

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

I have tried some solutions like: 我尝试了一些解决方案,如:

@ViewChild('focus') inputElement: ElementRef;

and in the button when I open the modal: 当我打开模态时按钮:

this.inputElement.nativeElement.focus();

or: 要么:

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

But in the first case the inputElement is undefined and in the second case nothing happen 但在第一种情况下,inputElement是未定义的,在第二种情况下,没有任何事情发生

I wrote a directive for this, with that an input field gets automatically focused when the modal opens. 我为此编写了一个指令,当模态打开时,输入字段会自动聚焦。

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();
        }
    }
}

In the html use it with: 在html中使用它:

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

You will need to use setTimeOut to workout.. 您将需要使用setTimeOut来锻炼..
though it shouldn't be undefined and your code of @ViewChild('focus') looks OK, but if it does not work then try changing the name from focus to some thing else...as focus is keyword as well... 虽然它不应该是未定义的,你的@ViewChild('focus')的代码看起来还不错,但如果它不起作用,那么尝试将名称从焦点更改为其他东西......因为焦点也是关键字......

Also I suggest do not mix Jquery and Angular... Not good practice. 另外我建议不要混合使用Jquery和Angular ......不是很好的做法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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