簡體   English   中英

在Angular2 / Javascript中初始化變量對象

[英]Initialize a variable object in Angular2 / Javascript

我來自Angular 1,我剛才這樣做:

var options = {};
options.location = "test";
options.time = "today";

我只是想用Angular 2做同樣的事情,通過將變量添加到對象並使用插值在HTML中引用它來“分組”我的變量

<input [(ngModel)]="options.location" />

現在我已經想到我可以做到這一點:

export class Options {
  location: string;
}

options: Options = {
  location: 'test'
};

我的問題:是否有更簡單的方法

options: {location: string};

謝謝!

Typescript可以被視為擴展JavaScript。 任何有效的JavaScript代碼都是有效的Typescript代碼。

您在問題中寫的代碼:

var options = {};
options.location = "test";
options.time = "today";

......完全合法(但不是最優)。

問題是,只需按照組件的方式聲明options ,就不會從模板中看到它。 options必須是Component類的公共成員。 您的Component類應該是這樣的

@Component({
  template: `
<input [(ngModel)]="options.location" />
`})
export class FormsPage {
  options = {location :"test", time : "today" }
}

請注意,如果我是你,除了Angular2之外,我還會閱讀Typescript文檔 (甚至是JavaScript 文檔 )。 它可以幫助您更好地理解如何處理它。

自己找到了 -

this.options = {location: "test"};

代替

this.options.location = "test"

不知道為什么第二個版本不起作用。 如果您有見解請分享評論!

要以角度初始化ngModel值,請創建類選項,如下所示:

Options.ts

export class Options {
  location: string;
  time: string;
  constructor(location: string, time: string) {

  }
}

要么

export class Options {
  location: string;
  time: string;
  constructor(location: string, time: string) {
    this.location = location;
    this.time = time;
  }
}

HTML:

<input type="text" name="location" [(ngModel)]="options.location" #location="ngModel" required/>

<input type="text" name="time" [(ngModel)]="options.time" #time="ngModel" required/>

在您的組件中初始化如下options

options = new Options('','');

注意 :如果您創建這樣的Options類:

   export class Options {
      constructor(location: string, time: string) {

      }
    }

它將與ng serveng build --prod作為AOT(Ahead-of-Time)編譯給出錯誤:

ERROR in ng:/xxxx/x.component.html (67,74): Property 'location' does not exist on type 'Options'.
ERROR in ng:/xxxx/x.component.html (72,72): Property 'time' does not exist on type 'Options'.

如果以這種方式初始化組件中的options

options={};

也會給出同樣的錯誤。

你可以這樣做:

options: Options = {
  location: 'test'
} as Options;

你可以這樣做:

Options = new Options ({ location :"test", time : "today"  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM