Antoine Olivier
Antoine Olivier

Reputation: 83

Can't get a basic for loop working in Typescript

I'm new to Typescript and Angular other than Angular 1. I'm just trying to do the basicest most basic for loop and it just won't work.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

    for (var i = 0; i < 5; i++) {
        console.log(i);
    }
}

I keep getting those errors.

ERROR in src/app/app.component.ts(10,7): error TS1138: Parameter declaration expected.
src/app/app.component.ts(10,28): error TS1005: ';' expected.
src/app/app.component.ts(13,1): error TS1128: Declaration or statement expected.

I tried a lot of synthaxes I found out on the internet but nothing works. Angular : 8.0.2 Angular CLI : 8.0.3 Node : 10.14.0

Upvotes: 0

Views: 349

Answers (1)

David Sherret
David Sherret

Reputation: 106630

For statements cannot be children of class declarations. This is not valid syntax:

export class AppComponent {
    for (var i = 0; i < 5; i++) {
        console.log(i);
    }
}

Move that into a method or constructor or somewhere else that allows a for statement to appear. For example:

export class AppComponent {
    constructor() {
        for (let i = 0; i < 5; i++) {
            console.log(i);
        }
    }
}

Upvotes: 3

Related Questions