2017-09-11 3 views
0

Ich muss ein Element innerhalb einer NGFOR-Schleife automatisch fokussieren.Autofokus funktioniert nicht im Winkel 4

Hier mein chat.component.html ist

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

Actualy, durch Taste klicken zeige ich diesen Chat Pop-up, ich brauche die letzte Chat-Autofokus.

Meine chat.ts Datei

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

ist es irgendwelche Vorschläge meiner Suche auf diesem Autofokus auf Google für Winkel 4.

+0

Können Sie Ihren ts-Code auch hinzufügen ..! –

+0

Danke @ dheeraj, ich habe meinen ts code hinzugefügt .. –

Antwort

0

autofocus Attribut, um am Ende funktioniert auf <button>, <input>, <keygen>, <select> und <textarea>. Lesen Sie diese documentation.

Sie müssen ein tabindex Attribut auf Ihrem span setzen und es manuell in ngAfterViewInit() fokussieren.

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

In Sie ts Code:

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

Link zu working demo.

+0

Hallo faisal, Wenn ich das ausführen, heißt es "Eigenschaft nativeElement existiert nicht auf Typ HTMLElement" –