【问题标题】:Autofocus not working in angular 4自动对焦在角度 4 中不起作用
【发布时间】:2018-02-19 12:52:18
【问题描述】:

我需要在 ngfor 循环中自动聚焦元素。

这是我的 chat.component.html

<div *ngFor="let chat of chats; let last = last">
  {{ chat.chat }} <span *ngIf="last;" autofocus></span>
</div>

实际上,通过使用按钮单击我正在显示此聊天弹出窗口,我需要自动聚焦最后一次聊天。

我的 chat.ts 文件

import {  Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import * as io from "socket.io-client";

@Component({
  selector: 'app-lsidebar',
  templateUrl: './lsidebar.component.html',
  styleUrls: ['./lsidebar.component.css']
})

export class LsidebarComponent implements OnInit {
  chat:String;
  showChat:Boolean;
  chats:any[];
  fanmateId:String;
  socket = io('http://localhost:3000');

  constructor(private authService:AuthService) { }

  ngOnInit() {

    this.showFans = false;
    this.showChat = false;
    this.getFanmates();
    this.chatss();
  }


  getChat(fanmateId,name){
    this.showChat = !this.showChat;
    this.chatname = name;
    this.fanmateId = fanmateId;
    const temp = {
        fanmate_id: fanmateId
    }
    this.getChats(temp);

  }
  getChats(temp){
    this.chats = [];
    this.authService.getChat(temp);

  }
  chatss(){
    this.socket.on('chatRes',function(chats){

      this.chats = chats.chats[0].messages;

    }.bind(this));

    this.socket.on('addChat',function(chats){

      this.chat = '';
      // console.log(chats);
    }.bind(this));
  }
}

有什么建议可以结束我在谷歌上自动对焦 angular 4 的搜索。

【问题讨论】:

  • 你也可以添加你的ts代码..!
  • 感谢@dheeraj,我添加了我的 ts 代码..

标签: angular angular2-template


【解决方案1】:

autofocus 属性适用于 &lt;button&gt;, &lt;input&gt;, &lt;keygen&gt;, &lt;select&gt;&lt;textarea&gt;。阅读此documentation

您需要在span 上设置tabindex 属性,并将其手动集中在ngAfterViewInit() 中。

<div *ngFor="let chat of chats; let last = last">
  {{ chat.chat }} 
  <span *ngIf="last;" #lastChat tabindex="9999"></span>
</div>

在你ts代码:

@ViewChild('lastChat') lastChat:HTMLElement;
ngAfterViewInit(){
    this.lastChat.nativeElement.focus();
  } 

链接到working demo

【讨论】:

  • 嗨,faisal,当我运行它时,它说“属性 nativeElement 在 HTMLElement 类型上不存在”
  • tabindex 属性真的有必要吗?
【解决方案2】:

将 tabindex 设置为元素并将其集中在您的 ts 文件中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 2018-09-14
    • 2015-11-14
    • 1970-01-01
    • 2017-12-12
    • 2018-09-09
    • 2022-01-19
    相关资源
    最近更新 更多