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

时间:2017-01-06 11:42:45

标签: html angularjs angular

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

这些是我的文件:

gamelobby.component.html:

<h2>Game Lobbies</h2>

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

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

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

有什么办法吗?

提前谢谢。

2 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:4)

您只需传递*ngFor迭代变量:

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