【问题标题】:Angular 2 select <li> and get the textAngular 2 选择 <li> 并获取文本
【发布时间】:2017-05-21 04:09:25
【问题描述】:

我正在做一个 angular2 项目,我正在为此苦苦挣扎...... 当我点击它时,我试图获取一里游戏大厅的文本。 有一张图片可以让您了解我所拥有的:

这些是我的文件:

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

我不知道该怎么做,我试着做 (click)="myMethod" 看看它是否会做点什么。但是我做错了……

有什么办法吗?

提前谢谢你。

【问题讨论】:

  • 你的(click)="myMethod"在哪里?

标签: html angularjs angular


【解决方案1】:

如果你尝试使用类似的东西会怎样:

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

【讨论】:

  • 非常感谢您的宝贵时间!
【解决方案2】:

您可以只传递*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);
  }
}

【讨论】:

    猜你喜欢
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2022-11-16
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多