自动对焦无法在角度4中工作

时间:2017-09-11 10:02:36

标签: angular angular2-template

我需要在ngfor循环中自动对焦一个元素。

这是我的chat.component.html

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

Actualy,通过使用按钮点击我显示此聊天弹出窗口,我需要自动对焦上次聊天。

我的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));
  }
}

是否有任何建议可以在google上以角度4结束我对此自动对焦的搜索。

2 个答案:

答案 0 :(得分:0)

autofocus属性适用于<button>, <input>, <keygen>, <select><textarea>。阅读此documentation

您需要在tabindex上设置span属性,并将其手动关注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

答案 1 :(得分:-1)

将tabindex设置为元素,并将其集中在ts fil