0

In my Angular app in my component.html I have a game board displayed by iteration of i and j:

<div class="board text-center">
        <div
          class="boardRow"
          *ngFor="
            let row of this.boards[this.clientsPlayerNumber];
            let i = index
          "
        >
          <div *ngFor="let box of row; let j = index">
            <div
              class="boardCell"
              [style.backgroundColor]="box.color"
              #cell
            ></div>
          </div>
        </div>
      </div>

Is there a chance to get in my component.ts any HTMLElement of this board cell, when not having interaction (events) in the view, but having only i and j in the component.ts?

Later on I want to use it to display animation having HTMLElement:

...
this.animateSprite(true, someViewElementHavingIandJ);
...

private animateSprite(isHit: boolean, ref: HTMLElement): void {
    this.displaySprite = true;
    this.spriteX = ref.offsetLeft - 50;
    this.spriteY = ref.offsetTop - 50;
    this.spriteUrl = isHit
      ? 'https://i.ibb.co/H4f84Wn/explode.png'
      : 'https://i.ibb.co/c3WLWN1/splash.png';
  }

Can I combine somehow #cell with i and j in the view, to use it later on as a @ViewChild('cell-i-j', { static: true }) cell-i-j: ElementRef;?

bakunet
  • 559
  • 8
  • 25
  • create a component for your cell with x and y as inputs. Use then `ViewChildren(CellCompoentn)` in host-component to select the instances of Cell-Components – enno.void Dec 21 '20 at 12:07
  • Here another solution based on a directive: https://stackoverflow.com/questions/40233844/angular2-querylist-based-on-element-class – enno.void Dec 21 '20 at 12:08
  • Regarding the first solution, how can I get then `HTMLElement` of the component i need? – bakunet Dec 21 '20 at 12:10
  • Within the CellComponent you need to select the HTMLElement via ref (#cell; @ViewChild('cell') cellNode; ) Then you can do `this.cellNode.nativeElement` – enno.void Dec 21 '20 at 12:14
  • Here as example: https://stackblitz.com/edit/angular-ivy-kxs4wc?file=src/app/app.component.ts – enno.void Dec 21 '20 at 12:38
  • It looks promissing with `ref: ElementRef;`, Ill have time to try it later on, and Ill come to you with this. Thank you – bakunet Dec 21 '20 at 12:42

0 Answers0