Angular 6 - ngModel在绑定显示数据时显示对象对象

时间:2018-06-04 22:18:23

标签: angular typescript angular6

我有一个名为“data”的变量,其中包含以下数据:

{
id: 1,
date: "2018-03-13T16:18:03",
date_gmt: "2018-03-13T16:18:03",
guid: {},
modified: "2018-05-03T17:25:36",
modified_gmt: "2018-05-03T17:25:36",
slug: "hello-world",
status: "publish",
type: "post",
title: {
rendered: "Hello world!"
},

...等

在我的app.component.html上,当我使用时,ID显示正常:

[ngModel]="data?.id"

当我尝试显示标题时出现问题。

当我尝试:

[ngModel]="data?.title.rendered"

我得到:[object Object]

但是当我使用时:

value="{{data?.title.rendered}}"

显示标题。

我怎样才能获得

[ngModel]="data?.title.rendered"显示标题而不是[object Object]

1 个答案:

答案 0 :(得分:2)

我做了这个stackblitz

组件中的

export class AppComponent {

  data = {
    id: 1,
    date: "2018-03-13T16:18:03",
    date_gmt: "2018-03-13T16:18:03",
    guid: {},
    modified: "2018-05-03T17:25:36",
    modified_gmt: "2018-05-03T17:25:36",
    slug: "hello-world",
    status: "publish",
    type: "post",
    title: {
      rendered: "Hello world!"
    }
  }

  myForm:FormGroup;
  constructor(private formBuilder: FormBuilder) {
        this.myForm = this.formBuilder.group({
            "title": ['', Validators.required]
        });      
    }
}

in html:

<form [formGroup]="myForm" >  
    <input type="text" class="form-control m-input" formControlName="title" name="title" id="title-field" placeholder="Title" [(ngModel)]="data?.title.rendered">
</form>