Last active
May 11, 2023 18:23
-
-
Save chaosmonster/c0bd9caee69ebbf6905e377cbf7650fd to your computer and use it in GitHub Desktop.
rough spreadsheet example with signals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, computed, Signal, signal, WritableSignal } from '@angular/core'; | |
import { bootstrapApplication } from '@angular/platform-browser'; | |
import { FormsModule } from '@angular/forms'; | |
import { NgFor } from '@angular/common'; | |
@Component({ | |
selector: 'app-root', | |
standalone: true, | |
imports: [ | |
NgFor, | |
FormsModule, | |
], | |
template: ` | |
<div *ngFor="let key of cellLabels"> | |
<div>{{key}}</div> | |
<div>input: | |
<input [ngModel]="cellValues.get(key)?.()" (ngModelChange)="cellValues.get(key)?.set($event)"> | |
</div> | |
<div>display: {{cellDisplays.get(key)?.()}}</div> | |
</div>` | |
}) | |
export class AppComponent { | |
cellLabels: string[] = []; | |
cellValues = new Map<string, WritableSignal<string>>(); | |
cellDisplays = new Map<string, Signal<string>>(); | |
rows = ['1','2','3']; | |
columns = ['A', 'B']; | |
constructor() { | |
for (const col in this.columns) { | |
for (const row in this.rows) { | |
const cellLabel = `${this.columns[col]}${this.rows[row]}`; | |
this.cellLabels.push(cellLabel); | |
const cellValue = signal(''); | |
this.cellValues.set(cellLabel, cellValue); | |
this.cellDisplays.set(cellLabel, computed(() => { | |
const value = cellValue(); | |
if (value.startsWith('=')) { | |
// this is by no means good code; an actual parser would be needed | |
// it is to illustrate what could be doable | |
const innerFn = value.substring(1); | |
if(innerFn.includes('+')) { | |
const summands = innerFn.split('+'); | |
const summandValues: number[] = []; | |
summands.forEach(summand => { | |
const innerCellDisplay = this.cellDisplays.get(summand.trim()); | |
if (innerCellDisplay) { | |
summandValues.push(Number(innerCellDisplay())); | |
} | |
}); | |
return `${summandValues.reduce((a, b) => a + b, 0)}`; | |
} | |
const innerCellDisplay = this.cellDisplays.get(innerFn); | |
return innerCellDisplay !== undefined ? innerCellDisplay() : 'issue'; | |
} else { | |
return value; | |
} | |
}) | |
) | |
} | |
} | |
} | |
} | |
bootstrapApplication(AppComponent); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment