Reputation: 2233
I recently started learning angular and wanted to create a slider.
I created an array of objects which will hold data for the sliders images and tried to display them in my components html file like this:
Ts file:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-slider',
templateUrl: './slider.component.html',
styleUrls: ['./slider.component.scss']
})
export class SliderComponent implements OnInit {
constructor() { }
ngOnInit() {
type sliderImgMeta = Array<{id:number,src:string,alt:string}>;
const arr: sliderImgMeta = [
{id: 1, src: './img/slider1', alt: 'alt1'},
{id: 2, src: './img/slider2', alt: 'alt2'},
{id: 3, src: './img/slider3', alt: 'alt3'}
]
}
}
And the html file:
<section id="slider">
<div id="slider-content">
<img src="{{arr[0].src}}" alt="{{arr[0].alt}}">
</div>
<div id="slider-navigation">
<span id="moveLeft"><</span>
<span id="moveRight">></span>
</div>
</section>
In return im getting ERROR TypeError: Cannot read property '0' of undefined
and unfortunetly have no idea how to resolve it.
Upvotes: 3
Views: 121
Reputation: 358
You define property in class for access from view.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-slider',
templateUrl: './slider.component.html',
styleUrls: ['./slider.component.scss']
})
type sliderImgMeta = Array<{id:number,src:string,alt:string}>;
export class SliderComponent implements OnInit {
arr: sliderImgMeta = [
{id: 1, src: './img/slider1', alt: 'alt1'},
{id: 2, src: './img/slider2', alt: 'alt2'},
{id: 3, src: './img/slider3', alt: 'alt3'}
];
constructor() { }
ngOnInit() {
}
}
Upvotes: 0
Reputation: 2966
you haven't arr
property in your class, instead you created variable in ngOnInit
which is accessible only inside it, try this way and note also that sliderImgMeta
type should be outside of class
import { Component, OnInit } from '@angular/core';
type sliderImgMeta = Array<{id:number,src:string,alt:string}>;
@Component({
selector: 'app-slider',
templateUrl: './slider.component.html',
styleUrls: ['./slider.component.scss']
})
export class SliderComponent implements OnInit {
arr: sliderImgMeta = [];
constructor() { }
ngOnInit() {
this.arr = [
{id: 1, src: './img/slider1', alt: 'alt1'},
{id: 2, src: './img/slider2', alt: 'alt2'},
{id: 3, src: './img/slider3', alt: 'alt3'}
]
}
}
Upvotes: 2