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

时间:2017-06-09 13:44:53

标签: angular angular2-template

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

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



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

    doAsync() {
        // do something async

        $(this.element.nativeElement).find('.error').focus();
    }
}




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

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

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

4 个答案:

答案 0 :(得分:12)

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

 import --> AfterViewInit

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


  ngAfterViewInit() {
    this.vc.nativeElement.focus();
  }
}

使用此组件html

<div #err class="alert alert-danger>{{errorPrompt}}</div>

答案 1 :(得分:0)

在异步函数的结果中,在组件上设置一个属性以显示或隐藏错误消息。

class MyComponent {

    hasErrors = false;
    errorPrompt = ""; 

    constructor() {}

    doAsync() {
        // do something async
        this.hasErrors = true;
        this.errorPrompt = "Fix the errors.";
    }
}

在标记中:

<div class="alert alert-danger" *ngIf="hasErrors">{{errorPrompt}}</div>

答案 2 :(得分:0)

不完全确定'。error'是什么类型的元素,但你可以尝试这样的事情:

class MyComponent {

    constructor(private renderer: Renderer2) { }

    doAsync() {
        // do something async

        setTimeout(() => {
            const element = this.renderer.selectRootElement('.error');
            if (element) {
                element.focus();
            }
        }, 200);
    }

}

如果元素嵌套在* ngIf中,我发现有时需要setTimeout。虽然不是最干净的解决方案,但它至少比包括jquery更好。您还可以为自动对焦参考定义自己的指令。

答案 3 :(得分:-4)

您可以使用类的角度指令:

<component1 [ngClass]="{focusClass: setFocus() }"></component1>

如果setFocus()返回true,则将焦点放在标记

中的类处于活动状态
相关问题