Angular2 array boolean
When declaring this:
public isCollapsedDet : boolean[][];
public isCollapsedCyc : boolean[] ;
I got the following error message:
/nestedForm/src/app/app.component.ts (95,7): Type 'boolean' is not assignable to type 'boolean[][]'.
I just need to get an array like this:
isCollapsedCyc[0] = true;
isCollapsedCyc[1] = false;
//
isCollapsedDet[0, 0] = true;
isCollapsedDet[0, 1] = true;
isCollapsedDet[1, 0] = false;
isCollapsedDet[1, 1] = true;
source to share
You cannot add values to an array by inserting them with a comma. Type boolean[][]
means there will be an array of arrays of boolean values, something like, for example:
[[true, false], [false, true]] // this is boolean[][] or Array<Array<boolean>>
if you want to set a value for it, you need to nest it in a regular array:
isCollapsedDet[0, 0] = true;
// error - comma has nothing to do there
isCollapsedDet[0][0] = true;
// success - element isCollapsedDet[0][0] in array isCollapsedDet[0] is true
More on arrays in TypeScript can be found here - and a few more advanced types here
Some helpful answers found here: Initializing Multidimensional Arrays
Other references: TypeScript Multidimensional Arrays
source to share
If you really only want the elements you mentioned, you can do:
let isCollapsedDet: boolean[][] = [[], []];
let isCollapsedCyc: boolean[] = [];
isCollapsedCyc[0] = true;
isCollapsedCyc[1] = false;
isCollapsedDet[0][0] = true;
isCollapsedDet[0][1] = true;
isCollapsedDet[1][0] = false;
isCollapsedDet[1][1] = true;
Or simply:
let isCollapsedDet: boolean[][] = [
[true, true], [false, true]
];
let isCollapsedCyc: boolean[] = [true, false];
which can be further reduced as the compiler will infer types based on initialization:
let isCollapsedDet = [
[true, true], [false, false]
];
let isCollapsedCyc = [true, false];
source to share
When you access a property in any class, and if you want to make it a member of the class, remember to include this
, and as David said you cannot assign values by splitting the indices withcomma(,)
export class HelloWorld implements OnInit{
// Declaring the variable for binding with initial value
yourName: string = '';
public isCollapsedDet : boolean[][] = [[], []];
isCollapsedCyc : boolean[] = [];
ngOnInit() {
this.isCollapsedCyc[0] = true;
this.isCollapsedCyc[1] = false;
//
this.isCollapsedDet[0][0] = true;
this.isCollapsedDet[0][1] = true;
this.isCollapsedDet[1][0] = false;
this.isCollapsedDet[1][1] = true;
}
}
source to share