如何使用angular2实现双向绑定

时间:2016-08-11 18:44:30

标签: angular

我对angular 2完全不熟悉,我试图将列表中的数据绑定到输入字段,我有一个div,在div中我有一个ul和一个输入字段,我想要做的是当我点击列出的每个名字时插入输入与数据绑定,我也想只有两个输入字段(现在每个列出的名称不是两个字段)

this is how it looks like

import { Component } from '@angular/core';
            import {MainService} from './main.service'

            @Component({
              selector: 'my-app',
              template:`
                <div  *ngFor="let user of data" (click)="message(user.name, user.number)">
                    <ul>
                        <li>{{user.name}}</li>
                    </ul>

                    Name: <input type="text" [(ngModel)]="user.name"><br><br>
                    number: <input type="text" [(ngModel)]="user.number">
                </div>

              `,
              providers: [MainService]
            })
            export class AppComponent {
                data: any[];
                constructor(private mainservice: MainService){

                }
                ngOnInit(){
                    console.log("Test")
                    this.getUsers()
                }
                getUsers(){

                    this.mainservice.getUsers().subscribe(
                        data => {
                            console.log(data)
                            this.data = data;
                            },
                        error => {
                            console.log(error)

                        }
                        )
                }
                message(name, num){
                    console.log(name + " " + num)
                }

             }

1 个答案:

答案 0 :(得分:0)

这是一个工作示例。我认为你的HTML错了。

@Component({
  selector: 'my-app',
  template:`
    <div  *ngFor="let user of data" (click)="EditUser(user)">
        <ul>
            <li>{{user.name}}</li>
        </ul>
    </div>
    Name: <input type="text" [(ngModel)]="model.name">
    <br /> <br />
    Number: <input type="text" [(ngModel)]="model.num">
  `,
  providers: [HTTP_PROVIDERS, MainService]
})

https://plnkr.co/edit/x1leEPz4w2rzV1LQyVkB?p=preview