简体   繁体   中英

binding data in Angular2

I have next template:

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

And controller:

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() {
   }

  }

I need pass data about current user when click button Show to another component. Here is my another component view:

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

And controller:

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() {
    }

}

I try to pass data, but when I do like this:

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

I got error: Can't bind to 'user' since it isn't a known property of 'strong'

How can I date object user to another component and how to render it?

A child component is a component inside another (parent component). I don't think that's what you want. With routerLink, you are trying to display a detail page.

routerLink sends your user to a new page, with a new url eg. /users/1 As well as clicking your link, they could just visit that url directly (eg. if it was bookmarked). So you can't just pass the user object internally.

Instead they get the user id from the url (route), and you then load that user inside the detail component. You would probably have a user service to do the loading so that both components can share that code.

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