[英]Why can't I perform 'certain' actions in export class?
當我嘗試在導出類中實現邏輯時,我有這個問題。 我可以聲明變量,但它們的行為是靜態的和最終的。當我嘗試使用普通的打字稿邏輯更改它們時,我會出錯。 為什么是這樣? 請參閱下面的示例:
但我想這無關緊要。
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"};
}
自請求以來的模塊
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"};
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.