Search code examples
javascriptarraysangularcomponents

Why can't I perform 'certain' actions in export class?


I have this question when I try to implent logic in export classes. I can declare variables but they behave static and final.When I try to change them with normal typescript logic, I get errors. Why is this? see the example here below:

  • land = counrty
  • landen = countries

but that is irrelevant I guess.

import { Component } from '@angular/core';
import { Land } from './model/land';


@Component({
  selector: 'app-root',
  //templateUrl: './app.component.html',
  template:`<h1>{{title}}</h1>
              <h2>Details van {{land.name}}</h2>
              <div><label>id: </label>{{land.id}}</div>
              <div>
                <label>naam: </label>
                <input [(ngModel)]="land.name" placeholder="name">
              </div>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  //this goes perfect
  landen: Land[] = [
    {id: 1, name:"Belgium"},
    {id: 2, name: "Holland"}
  ];

//if declare array like below and then insert values, it doesn't work
  landen: Land[] = [];
  landen[0] = {id: 1, name:"Belgium"};
  landen[1] = {id: 2, name:"Holland"};

}

module since requested

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

@NgModule({
 declarations: [
   AppComponent
 ],
 imports: [
   BrowserModule,
   AppRoutingModule,
   FormsModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }



Solution

  • You can't run code inside a class definition, you will want to put your assignment code into the constructor. behave static and final indeed, that's another issue with it, you have a global instance of {id: 1, name:"Belgium"}, that your adding to this list, change any one instance of this list, and all will change. - Keith

    import { Component } from '@angular/core';
    import { Land } from './model/land';
    
    
    @Component({
      selector: 'app-root',
      //templateUrl: './app.component.html',
      template:`<h1>{{title}}</h1>
                  <h2>Details van {{land.name}}</h2>
                  <div><label>id: </label>{{land.id}}</div>
                  <div>
                    <label>naam: </label>
                    <input [(ngModel)]="land.name" placeholder="name">
                  </div>`,
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    
      //this goes perfect
      landen: Land[] = [
        {id: 1, name:"Belgium"},
        {id: 2, name: "Holland"}
      ];
    
      constructor(){
        landen[0] = {id: 1, name:"Belgium"};
        landen[1] = {id: 2, name:"Holland"};
      }
    }