代码之家  ›  专栏  ›  技术社区  ›  barteloma

如何将角度属性绑定到模型作为数组?

  •  0
  • barteloma  · 技术社区  · 5 年前

    我的组件是

    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 ] } }
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   Sravan    5 年前

    你能这样试一下吗,

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