I'm attempting to input data into a child component which is an object within an object. I have 2 Models:
Tiles:
import { Tile } from "./tile";
export class Tiles {
public tileOne: Tile;
}
Tile
export class Tile {
public squareId: number;
}
My parent class, Board
export class BoardComponent implements OnInit {
constructor() { }
ngOnInit() {
const tiles = new Tiles();
tiles.tileOne = new Tile();
tiles.tileOne.squareId = 1;
}
}
and the template:
<div class="row row-1">
<square class="square-component" [tile]="tiles.tileOne"></square>
</div>
and the child class, square :
export class SquareComponent implements OnInit {
@Input() tile: Tile;
constructor() { }
ngOnInit() {
}
}
The console is throwing this error:
'ERROR TypeError: Cannot read property 'tileOne' of undefined'
Which I don't understand why tileOne
would be 'undefined'
as it's initialized in the ngOnInit
of the board class.
Any help would be appreciated.
Add a safe navigation operator to check if the value is there,
<square class="square-component" [tile]="tiles?.tileOne"></square>
EDIT
You need to assign the value using this
ngOnInit() {
const tiles = new Tiles();
tiles.tileOne = new Tile();
tiles.tileOne.squareId = 1;
this.tiles = tiles;
}
At least in the code that you provided the tiles object is not assigned to the component. Thus, it will not be available in the template. Try:
public tiles: Tiles;
ngOnInit() {
const tiles = new Tiles();
tiles.tileOne = new Tile();
tiles.tileOne.squareId = 1;
this.tiles = tiles;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.