2017-09-11 8 views
0

で働いていない私はngforループ内の要素をオート​​フォーカスする必要があります。は、オートフォーカスの角4

はここに私の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)); 
    } 
} 

は角4

+0

あなたは同様にあなたのtsコードを追加することができます..! dheeraj @ –

+0

おかげで、私は私のtsコード.. –

答えて

0

autofocus属性についてGoogleでこのオートフォーカスでの私の検索を終了するために何か提案があり<button>, <input>, <keygen>, <select><textarea>上で動作しますファイル。このdocumentationを読んでください。

spantabindex属性を設定し、手動でngAfterViewInit()にフォーカスする必要があります。あなたtsコードで

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

working demo

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

リンク。

+0

こんにちはファイサル、私はこれを実行すると、それは「プロパティnativeElementがタイプのHTMLElement上に存在しない」と言うを追加しました –