【问题标题】:how to get ngModel value which is inside of ngFor?如何获取 ngFor 内部的 ngModel 值?
【发布时间】:2016-10-21 07:52:16
【问题描述】:
<div class="form-horizontal" style="margin:auto;" *ngFor="#cmp of getUser">
    <div class="form-group">
        <label class="col-md-3 control-label">Name:</label>
        <div class="col-md-8">
            <input type="text" class="form-control" id="cname" [(ngModel)]="cmp.name"/>
        </div>
    </div>
<button class="slds-button slds-button--neutral slds-button--brand" (click)="updateUser(cmp)">Save</button>
</div>

在这里,通过在 ngFor 中使用 ngModel,我可以显示数据,但是如果我想更新/编辑此显示数据,那该怎么做呢?

updateUser(){     
    var body=JSON.stringify({

         name:this.cmp.name,
        //what to do here????
    })
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    this.http.post('../update.php?id='+matches['id'],body,{
            headers:headers;
    })
     .map(res => res.json())
     .map((res) => {
                    if (res.success) {
                        this.message = res.message;
                    }
                    else{
                        this.err="Something went wrong";
                    }

        })
        .subscribe(
            data=>this.updUser=JSON.stringify(data),
            error=>alert(error),
            msg=>console.log("done"));
    }

在这个 updateUser 函数中,我想更新数据。但是当我这样做时,它向我显示了 cmp 未定义的错误。那么如何在 post 方法中使用来自 [(ngModel)]=cmp.name 的值???

【问题讨论】:

  • 您使用的是哪个版本的 Angular 2?在最新版本中,它应该是 let cmp of getUser 而不是 #cmp
  • @AlexanderCiesielski 我正在使用 angular2: 2.0.0-beta.14 版本

标签: angular angular2-ngmodel


【解决方案1】:

*ngFor="#cmp of getUser" 更改为*ngFor="let cmp of getUser" 并检查updateUser 内部的函数,如下所示,如果您获得了已更改的值:

updateUser(data:any){
  console.log(data);

  // if it works you can add your code here to call API
}

【讨论】:

  • 我需要使用 # 否则它会告诉我 ngFor 不是原生属性
  • 我没有在 console.log() @ranakrunal9 中得到任何东西
猜你喜欢
  • 2016-11-20
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 2021-07-30
  • 2018-11-24
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
相关资源
最近更新 更多