首页 > 解决方案 > 在悬停/单击时显示文本以写入 HTML 表格

问题描述

我有与组件字段连接的 HTML 表gameArray,我会:

我已经对其进行了编码,它在 Firefox 中完美运行,在 Chrome 中存在一些问题。问题是:当我单击第 0 列或第 1 列时,下一列中将显示“H”。

很高兴看到你的建议。问候!

工作应用程序示例:

https://angular-idfr1g.stackblitz.io

app.component.html

    <hello name="{{ name }}"></hello>
      <table>
        <tr *ngFor='let row of gameArray; let i = index'>
          <td *ngFor='let column of gameArray[i]; let j = index'
              (click)="selectFieldHandler(i, j)"          
              appHoverDirective>{{ gameArray[i][j] }}</td>
        </tr>
      </table>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  gameArray = [
    ['', '', ''],
    ['', '', ''],
    ['', '', '']
  ];

  selectFieldHandler(row: number, col: number): void{
    this.gameArray[row][col] = "clicked";
  }
}

hover-directive.ts

import { Directive, ElementRef, HostListener, OnInit } from '@angular/core';

@Directive({
  selector: '[appHoverDirective]'
})
export class HoverDirective implements OnInit {

  markToDisplay: string = 'H';
  currentElement;

  constructor(
    private _element: ElementRef
  ){}

  ngOnInit(): void {}

  @HostListener('mouseenter') onMouseEnter() {
    if ( this._element.nativeElement.textContent === "" ) {
      this.currentElement = this._element.nativeElement;
      this._element.nativeElement.style.color = '#00274a96';
      this._element.nativeElement.textContent = this.markToDisplay;
    }
  }

  @HostListener('mouseleave') onMouseLeave() {
    if ( this._element.nativeElement === this.currentElement ) {
      this._element.nativeElement.textContent = '';
    }
  }

}

标签: javascripthtmlangulartypescriptangularjs-directive

解决方案


解决方案:

单击后,我需要清除指令中的 td textContent。

  @HostListener('click') onMouseClick() {
    if ( this._element.nativeElement === this.currentElement ) {
      this._element.nativeElement.textContent = '';
    }
  }

推荐阅读