Reputation: 384
I am creating a component which represents the days of the week. I am trying eastablish whether one of the days has been selected by using bitwise arithmetic (may be this belongs in coding golf?).
However, the Angular compiler complains that the &
symbol should not be in the template expression. What am I doing wrong? I have tried substituting &
with &
, and also have found a couple of questions that deal with this, but for the |
(OR) operation only.
Thanks in advance.
days-run.componenent.html
<div>
<p>Filter on days run</p>
<table>
<tr>
<td (click)='click(1)' [class.selected]='daysRun & 1'>M</td>
<td (click)='click(2)' [class.selected]='daysRun & 2'>T</td>
<td (click)='click(3)' [class.selected]='daysRun & 4'>W</td>
<td (click)='click(4)' [class.selected]='daysRun & 8'>H</td>
<td (click)='click(5)' [class.selected]='daysRun & 16'>F</td>
<td (click)='click(6)' [class.selected]='daysRun & 32'>S</td>
<td (click)='click(7)' [class.selected]='daysRun & 64'>U</td>
<td> {{ daysRun }} </td>
</tr>
</table>
</div>
days-run.component.ts
import { Component, OnInit } from '@angular/core';
import { ModelService } from './../model/model.service'
@Component({
selector: 'app-days-run',
templateUrl: './days-run.component.html',
styleUrls: ['../controlsCommon.css','./days-run.component.css'],
providers: [ModelService]
})
export class DaysRunComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
// 1 = Monday, 2 = Tuesday, 4 = Weds, 8 = Thurs, 16 = Fri, 32 = Sat, 64 = Sun
daysRun = 0;
daysRunString = "MO";
click(daysRun : number) : void {
// Toggles bit 0 - 6 using XOR (^) operator
this.daysRun ^ (Math.pow(2, daysRun - 1));
}
}
Upvotes: 1
Views: 746
Reputation: 2080
No easy way to work around this, I just declared a hasFlag() function in my component class. I tried to extend Number's prototype to make it work like .NET's but TypeScript doesn't seem to realize the extended functions can be used with enums, plus it's probably a bad idea to mess with built in prototypes anyway.
hasFlag(x: number, flag: number): boolean {
return (x & flag) === flag;
}
<myTag [myAttribute]="hasFlag(myVariable, 1)" />
You can alternatively just have it only use the bitwise and if you need to do more math on the result, but this is the common case of using it I think.
Upvotes: 0