简体   繁体   English

Angular 2 Material 输入焦点不起作用

[英]Angular 2 Material input focus not working

The inputs are inside of a modal dialog.输入位于模态对话框内。 I have no idea why it is not working.我不知道为什么它不起作用。 I looked at the official docs and it listed focus as something you can pass to the element but it's not working?我查看了官方文档,并将焦点列为您可以传递给元素的内容,但它不起作用?

Does anyone know why?有谁知道为什么?

Angular Material - Input Docs角材料 - 输入文档

<form class="example-form">

  <md-input-container class="example-full-width" style="width: 300px; padding: 5px; border-radius: 10px;">
    <input mdInput type="email" name="to" placeholder="Email">
    <md-error></md-error>
  </md-input-container>

  <md-input-container focus focused>
    <input mdInput type="text" name="a" placeholder="zzzz" focus focused (focus)="">
  </md-input-container>

</form>

Your attempts do not work because:您的尝试无效,因为:

  • focused is a property driving the mat-focused class on mdInputContainer . focused是推动在垫子上,重点类的属性mdInputContainer You can use it to know whether your input is focused or not.您可以使用它来了解您的输入是否集中。 You cannot use it to change the focus state.您不能使用它来更改焦点状态。
  • focus is a method on mdInput that lets you programmatically focus the input. focusmdInput上的一种方法,可让您以编程方式聚焦输入。 You can call the myInput.focus() with myInput being something like ViewChild('myInput') for instance.例如,您可以调用myInput.focus()其中myInput类似于ViewChild('myInput')

But the simplest way to achieve what you want is to use the standard autofocus attribute :但实现您想要的最简单方法是使用标准的autofocus属性:

<md-input-container>
    <input mdInput type="text" name="a" placeholder="zzzz" autofocus>
</md-input-container>

Have you try with cdkFocusInitial which will specify the element that will receive focus upon initialization您是否尝试使用cdkFocusInitial它将指定将在初始化时获得焦点的元素

documentation can be found here文档可以在这里找到

<form class="example-form">
  <md-input-container class="example-full-width" style="width: 300px; padding: 5px; border-radius: 10px;">
    <input mdInput #emailInput="matInput" type="email" name="to" placeholder="Email">
    <md-error></md-error>
  </md-input-container>
</form>

Then in the controller:然后在控制器中:

@ViewChild('emailInput') searchInput: MatInput;
....
ngAfterViewInit() {
  this.emailInput.focus();
}

What this.emailInput.focus() does is actually "elementRef.nativeElement.focus()" https://github.com/angular/material2/blob/master/src/lib/input/input.ts#L287 this.emailInput.focus() 实际上是“elementRef.nativeElement.focus()” https://github.com/angular/material2/blob/master/src/lib/input/input.ts#L287

so you could do that your self like:所以你可以这样做你自己喜欢:

this.emailInput.nativeElement.focus()

I was struggling with the same issue.我正在努力解决同样的问题。 I was using F6 to open the dialog and I could not get the <input> to get focus.我正在使用 F6 打开对话框,但无法获得<input>以获得焦点。 It turned out that I wasn't preventing the default behavior of F6 and F6 highlights the browser URL window;事实证明,我并没有阻止 F6 的默认行为,而 F6 会突出显示浏览器 URL 窗口; so it was stealing focus.所以它正在窃取焦点。

switch (event.keyCode) {
      case 117:
        event.preventDefault();
        this.openAddAveragesDialog();
        break;
      default:
        return;
    }

Also, no magic tag attribute works.此外,没有魔术标签属性有效。 Autofocus, Focused, Focus, whatever, no dice.自动对焦,对焦,对焦,不管怎样,没有骰子。 I had to create a directive and use that in my input element.我必须创建一个指令并在我的输入元素中使用它。 I got help with that using this answer.我使用这个答案得到了帮助。

Here is the element after adding the directive (numberOnly is another directive for only number input):这是添加指令后的元素(numberOnly 是另一个仅用于数字输入的指令):

<md-input-container> <input mdInput [focus]="true" [numberOnly]="true"/></md-input-container>

**Edit : Adding Directive code as suggested by @Mackelito for clarity. **编辑:为了清晰起见,按照@Mackelito 的建议添加指令代码。 Here is the directive I wrote using the answer I linked above.这是我使用上面链接的答案编写的指令。 Keep in mind material has changed their tag labels to <input matInput> from <input md-input>请记住,材料已将其标签标签从<input md-input>更改为<input matInput> <input md-input>

import {Directive, ElementRef, Inject, Input, OnChanges, OnInit,     Renderer} from '@angular/core';

@Directive({
  selector: '[focus]'
})

export class FocusDirective implements OnChanges, OnInit {
@Input()
focus: boolean;

constructor(@Inject(ElementRef) private element: ElementRef, public renderer: Renderer) {}

ngOnInit() {
    this.renderer.invokeElementMethod(this.element.nativeElement,   'focus', []);
}

public ngOnChanges() {
this.element.nativeElement.focus();
}

} 

You can usually set focus without any Typescript code, using the Template markup.您通常可以使用模板标记在没有任何 Typescript 代码的情况下设置焦点。 But in the case of a Dialog, you'll need to use @Mackelito's solution with @ViewChild and ngAfterViewInit() .但是在 Dialog 的情况下,您需要将@Mackelito 的解决方案与@ViewChildngAfterViewInit()

I had to focus a TextArea that's inside a Menu, when that Menu appears.当 Menu 出现时,我必须聚焦在 Menu 内的 TextArea。 Fortunately, Menu has a (menuOpened) event I could bind to.幸运的是,Menu 有一个我可以绑定的 (menuOpened) 事件。

  <button mat-stroked-button color="accent" [matMenuTriggerFor]="addMenu"
    (menuOpened)="newTypes.focus()">
    Add
    <mat-icon class="dyna-dropdown-arrow">arrow_drop_down</mat-icon>
  </button>
  <mat-menu #addMenu="matMenu" [overlapTrigger]="false">
    <form [formGroup]="formGroup" (ngSubmit)="onFormSubmit()" novalidate (keydown.tab)="$event.stopPropagation()">
      <mat-form-field appearance="outline" (click)="$event.stopPropagation(); false;">
        <mat-label>New Pay Types</mat-label>
        <textarea #newTypes rows="6" matInput placeholder="New Pay Types" [formControl]="formGroup.controls['payTypes']" required></textarea>
        <mat-hint>Enter multiple Pay Types, separated by newlines</mat-hint>
        <mat-error *ngIf="formGroup.controls['payTypes'].invalid">Required</mat-error>
      </mat-form-field>
      <div fxLayout="row-reverse" fxLayoutGap="8px" fxLayoutAlign="start center">
        <button mat-stroked-button color="accent" type="submit" [disabled]="!formGroup.valid">Add</button>
        <button mat-button type="button">
          Cancel
        </button>
      </div>
    </form>
  </mat-menu>

The important part here is the (menuOpened)="newTypes.focus()" and we see the newTypes is a TemplateRef variable attached to the TextArea I want to focus marked as <textarea #newTypes .这里的重要部分是(menuOpened)="newTypes.focus()" ,我们看到newTypes是一个 TemplateRef 变量,附加到我想要关注的 TextArea 上,标记为<textarea #newTypes

Here's a screen shot that shows my menu opening up and it immediately gets focus to the Textarea inside it.这是一个屏幕截图,显示我的菜单打开,它立即获得焦点到其中的 Textarea。

在此处输入图片说明

In input tag type cdkFocusInitial在输入标签类型cdkFocusInitial

<input matInput [(ngModule)]="cityName" cdkFocusInitial>

That set its work 100%那设置它的工作 100%

If u won't to more info click here如果您不想了解更多信息,请单击此处

Try to add some delay before set the input get focus.尝试在设置输入获取焦点之前添加一些延迟。 I've made this behavior a directive for your reference.我已将此行为作为指令供您参考。

delay-focus.ts延迟焦点.ts

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

@Directive({
  selector: '[delayFocus]'
})
export class DelayFocusDirective {

  @Input() delayFocusInterval;
  @Input() set delayFocus(condition: boolean) {
    if (condition) {
      console.log(this.delayFocusInterval);
      setTimeout(() => {
        this.el.nativeElement.focus();
      }, this.delayFocusInterval | 500);
    }
  }
  constructor(private el: ElementRef) { }
}

example例子

<input type="text" placeholder="Delay 100ms to get focus" delayFocus="true" delayFocusInterval="100">

You can try it here .你可以在这里试试。

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

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