为什么我无法在导出类中执行"某些"操作?



当我尝试在导出类中实现逻辑时,我遇到了这个问题。我可以声明变量,但它们表现为静态和final。当我试图用正常的typescript逻辑更改它们时,我得到了错误。为什么会这样?请看下面的例子:

  • land = country
  • landen =国家

但我想这是无关的。

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 { }

您不能在类定义中运行代码,您需要将赋值代码放入构造函数中。behave static and final,这是它的另一个问题,你有一个{id: 1, name:"Belgium"},的全局实例,你把它添加到这个列表中,改变这个列表的任何一个实例,所有的都会改变。——基思

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"};
}
}

相关内容

  • 没有找到相关文章

最新更新