繁体   English   中英

在Angular2中绑定数据

[英]binding data in Angular2

我有下一个模板:

   <table width="700">
    <caption>All Users</caption>
    <thead>
        <tr>
            <th>name</th>
            <th>surname</th>
            <th>age</th>
            <th>action</th>
        </tr>
    </thead>
    <tbody>
        <tr  *ngFor="let user of users">
            <td [class] = "user">{{ user.name}}</td>
            <td >{{ user.surname}}</td>
            <td >{{ user.age}}</td>
            <td>
                <a  routerLink = "{{user.id}}" class="btn btn-info"><strong (click) = "clickShow(user)">show</strong></a>
            </td>
        </tr>
    </tbody>
</table>

和控制器:

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

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

json = `[{
    "id": 1,
    "name" : "John",
    "surname" : "Walsh",
    "age" : "23"
},{
    "id": 2,
    "name" : "Mike",
    "surname" : "Mikic",
    "age" : "25"
}]`;

users = JSON.parse(this.json);
user: any;
constructor(){
}
   clickShow(user){
      this.user = user;
   }

ngOnInit() {
   }

  }

单击“显示到另一个组件”按钮时,我需要传递有关当前用户的数据。 这是我的另一个组件视图:

<h1>Show user</h1>
<span>{{ user.name }}</span>
<span>{{ user.surname }}</span>
<span>{{ user.age }}</span>

和控制器:

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-show',
  templateUrl: './show.component.html',
  styleUrls: ['./show.component.css']
})
export class ShowComponent implements OnInit {

    @Input() user;

    constructor() { 
    }
    ngOnInit() {
    }

}

我尝试传递数据,但是当我这样做时:

 <a  routerLink = "{{user.id}}" class="btn btn-info"><strong [user] = "user" (click) = "clickShow(user)">show</strong></a>

我收到错误消息:无法绑定到“用户”,因为它不是“强”的已知属性

如何将对象用户与另一个组件约会以及如何呈现它?

子组件是另一个组件(父组件)内部的组件。 我认为那不是你想要的。 使用routerLink,您试图显示详细信息页面。

routerLink将您的用户发送到带有新网址的新页面,例如。 / users / 1除了单击您的链接之外,他们也可以直接访问该URL(例如,如果已将其添加为书签)。 因此,您不能只在内部传递用户对象。

相反,他们从url(路线)获取用户ID,然后将用户加载到详细信息组件中。 您可能需要用户服务来进行加载,以便两个组件都可以共享该代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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