角度2 - 将焦点设置为元素

Eag*_*arn 4 angular2-template angular

我有一个异步/ http调用,并且如果异步调用导致错误,则希望将焦点设置为模板中的错误元素.

  • 一种方法是注入ElementRef,然后使用JQuery访问元素并在其上调用focus()方法.

class MyComponent {
   
    constructor(private element: ElementRef) {}

    doAsync() {
        // do something async

        $(this.element.nativeElement).find('.error').focus();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 另一种方法可能是创建一个指令,它绑定到模型上的属性并在host元素上调用focus()方法.

在角度2中包含/使用JQuery有多好?

另外,我认为Angular的工作方式(MV*)是" 修改视图反应模型 ".那么,哪一个是正确的方法呢?

yal*_*esh 12

让我们在你的焦点组件中尝试这个

 import --> AfterViewInit

 export class YourComponent implements AfterViewInit {
   @ViewChild('err') vc: any;


  ngAfterViewInit() {
    this.vc.nativeElement.focus();
  }
}
Run Code Online (Sandbox Code Playgroud)

使用这个组件html

<div #err class="alert alert-danger>{{errorPrompt}}</div>
Run Code Online (Sandbox Code Playgroud)