I am using Angular7 and have a custom class which contains a number and an array of string.
export class Page {
constructor(id: number, keywords: string[]) {}
}
Now i created an array of this object in my component and intialised it.
import {Page} from '../page';
export class SearchComponent implements OnInit {
pages: Page [];
constructor() { }
ngOnInit() {
this.pages = [
{id:'1', Keywords:['abc', 'bca','klj']},
{id:'2', Keywords:['asas', 'aaa']},
{id:'3', Keywords:['dasd', 'asd']}
];
consol.log(this.pages[0].keywords);
consol.log(this.pages[0].id);
}
}
I want to access the id, and keywords array, but this code shows compilation error saying:
Property 'id' does not exist on type 'Page' and Property 'keywords' does not exist on type 'Page'.
page.ts, replace the code with:export interface Page { id: string, keywords: string[] }. then take care to the case ofkeywords.this.pages = [new Page(1, ["a", "b"]), new Page(2, ["c", "d"])]. Then in the Page's constructor, you must keep the parameters as properties by adding thepublicaccessor:constructor(public id: number, public keywords: string[]) {}.