如何绑定角度属性以建模为数组?

时间:2019-12-17 12:33:05

标签: angular typescript angular8

我的组件是

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

export class LocationModel {
  name: string;
  position: { 
    center: any[]
  }
} 

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  model: LocationModel = new LocationModel();

  onSubmit() {    
    console.log(this.model);
  }
}

HTML组件模板是:

<form (ngSubmit)="onSubmit(f)">
 Location name: 
 <input 
   type="text"
   [(ngModel)]="model.name"
   name="firstName"><br>
lon: 
 <input 
   type="text" 
   [(ngModel)]="model.positon.center[1]"
   name="lon"><br>
lat:
 <input 
   type="text" 
   [(ngModel)]="model.positon.center[0]"
   name="lat"><br>
 <input type="submit" value="Submit">
</form>

{{model|json}}

但是我无法创建如下的json模板:

{ "name": "some name", "position": { "center": [ 30.6067, 490.5563189 ] } }

1 个答案:

答案 0 :(得分:0)

您能这样尝试吗?

initial value分配给center

export class LocationModel {
  name: string;
  position: { 
    center: ["",""]
  }
} 

HTML:

<form (ngSubmit)="onSubmit(f)">
 Location name: 
 <input 
   type="text"
   [(ngModel)]="model.name"
   name="firstName"><br>
lon: 
 <input 
   type="text" 
   [(ngModel)]="model.positon.center[1]"
   name="lon"><br>
lat:
 <input 
   type="text" 
   [(ngModel)]="model.positon.center[0]"
   name="lat"><br>
 <input type="submit" value="Submit">
</form>

{{model|json}}