Angular 2选择<li>并获取文本

Joã*_*lva 1 html angularjs angular

我正在做一个angular2项目,我正在努力解决这个问题...当我点击它时,我正试图获得游戏大厅的文字.有一张图片可以让您了解我拥有的内容: 在此输入图像描述

这些是我的文件:

gamelobby.component.html:

<h2>Game Lobbies</h2>

<div class='games'>
    <ul>
        <li *ngFor="let m of gameLobby">{{m}}</li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

gamelobby.component.ts:

import { Component, OnInit } from '@angular/core';
import { WebSocketService } from '../services/websocket.service';


@Component({
    moduleId: module.id,
    selector: 'gamelobby',
    styleUrls: [ 'gamelobby.component.css' ],
    templateUrl: 'gamelobby.component.html'
})
export class GameLobbyComponent implements OnInit{

    gameLobby: string[] = [];  
    mouseover:boolean = false;

    constructor(private websocketService: WebSocketService) {
    }

    ngOnInit() {
        this.websocketService
            .getLobbies()
            .subscribe((m:any) => this.gameLobby.push(<string>m));
    }      
}
Run Code Online (Sandbox Code Playgroud)

我不知道怎么能这样做,我试着做(点击)="myMethod"来看它是否会做某事.但我做错了......

有什么办法吗?

先感谢您.

fed*_*zzi 7

如果您尝试使用以下内容怎么办?

<h2>Game Lobbies</h2>

<div class='games'>
    <ul>
        <li *ngFor="let m of gameLobby" (click)="getValue(m)">{{m}}</li>
    </ul>
</div>


import { Component, OnInit } from '@angular/core';
import { WebSocketService } from '../services/websocket.service';


@Component({
    moduleId: module.id,
    selector: 'gamelobby',
    styleUrls: [ 'gamelobby.component.css' ],
    templateUrl: 'gamelobby.component.html'
})
export class GameLobbyComponent implements OnInit{

    gameLobby: string[] = [];  
    mouseover:boolean = false;

    constructor(private websocketService: WebSocketService) {
    }

    ngOnInit() {
        this.websocketService
            .getLobbies()
            .subscribe((m:any) => this.gameLobby.push(<string>m));
    }  

    getValue = (item : string) =>{
        console.log(item);
    }
}
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 5

You can just pass the *ngFor iteration variable:

<div class='games'>
    <ul>
        <li *ngFor="let m of gameLobby" (click)="myMethod(m)">{{m}}</li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)
class GameLobbyComponent {
  myMethod(m) {
    console.log(m);
  }
}
Run Code Online (Sandbox Code Playgroud)