如何不使用ngFor打印响应

时间:2019-02-06 15:11:43

标签: angular

这是我的功能,工作正常

function(id){
    this.myservice
      .getUserById(id).subscribe(
        result => {
          this.myDatabyId = result.json();
        },
        error => {
          console.log(error.json());
        }
      );
  }

响应就是这样

[
  {
    "role": "admin",
    "_id": "5c2dc074d6bfba36b41b34de",
    "name": "admin",
    "email": "admin@gmail.com",
    "username": "admin",
  }
]

如何在模板中打印此内容

{{myDatabyId | json}}
<div class="modal-body">
   <form name="form" novalidate *ngFor="let item of myDatabyId">
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" name="name"  [(ngModel)]="item.name" required />
        </div>
        <div class="form-group">
                <label for="email">Email</label>
                <input type="text" class="form-control" name="email"  [(ngModel)]="item.email" required />
        </div>
        <div class="form-group">
                <label for="username">Username</label>
                <input type="text" class="form-control" name="username"  [(ngModel)]="item.username" required />
        </div>
        <div class="form-group">
                <label for="role">Role</label>
                <input type="text" class="form-control" name="role"  [(ngModel)]="item.role" required />
        </div>
    </form>

我用* ng表示错误,因为它总是一个,而不总是一个

我也尝试获取ngModel值

<button type="button" class="btn btn-primary" (click)="confirm()">OK</button>

confirm(){
    console.log("Confirm",name);
  }

它返回未防御状态

1 个答案:

答案 0 :(得分:1)

如果只有一项,则可以维护单个对象而不是数组。

代码:

myDatabyId;

function(id){
    this.myservice
      .getUserById(id).subscribe(
        result => {
          this.myDatabyId = result.json()[0];  // get first item from an array
        },
        error => {
          console.log(error.json());
        }
      );
  }

在您的html中-您可以执行[(ngModel)]="myDatabyId.name"

<div class="modal-body" *ngIf="myDatabyId">
   <form name="form" novalidate>
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" name="name"  [(ngModel)]="myDatabyId.name" required />
        </div>
        <div class="form-group">
                <label for="email">Email</label>
                <input type="text" class="form-control" name="email"  [(ngModel)]="myDatabyId.email" required />
        </div>
       <div class="form-group">
                <label for="username">Username</label>
                <input type="text" class="form-control" name="username"  [(ngModel)]="myDatabyId.username" required />
        </div>
        <div class="form-group">
                <label for="role">Role</label>
                <input type="text" class="form-control" name="role"  [(ngModel)]="myDatabyId.role" required />
        </div>
    </form>