简体   繁体   中英

How to bind angular property to model as array?

My component is

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

And HTML component template is:

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

But I could not create a json template like following:

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

Can you please try like this,

Assigning initial value to 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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM