Angular2 - 在执行下拉值选择时将动态加载的参数传递给函数

时间:2017-02-23 15:30:09

标签: javascript html twitter-bootstrap angular

请检查一下,我是否以正确的格式传递 li 标记点击 updateId 方法的参数?控制台中的错误仅显示该行....

我的app.component.html代码是

<div class='form-group' style="width: 100%;">
    <div class="btn-group" style="width: 100%;">
        <button type="button" class="btn btn-default" style="width : 75%;text-align: left;">{{name}}</button>
        <button type="button" data-toggle="dropdown" class="btn btn-default dropdown-toggle"><span class="caret"></span></button>
        <ul class="dropdown-menu" style="width: 75%;">
             <li *ngFor="let result of jsonList" ><a class="dropdown-item" (click)="updateId('{{result.id}}', '{{result.name}}')" >{{result.name}}</a>
            </li>
        </ul>
    </div>
</div>

我的app.component.ts是,

import { HomeService } from '../../services/home.service';
import { Component, OnInit } from '@angular/core';

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

  id: string;
  name : string;
  jsonList : any;

  constructor(private homeservice: HomeService) { }

  ngOnInit() {
    this.id = null;
    this.name = "SELECT";
    this.jsonList= [{"Id" : "F1", "name" : "FONE"}, {"id" : "F2", "name" : "FTWO"}]
  }



  updateId(id : string, name : string) : void {
        this.id = id;
        this.name = name;
  }

}

它不起作用。错误发生在 li 标记单击函数方法中,该方法从 jsonList 传递动态参数。所以请帮助我解决问题。

2 个答案:

答案 0 :(得分:1)

不要在事件绑定(例如{{ }}属性)中使用句柄(click) - 它们将自动针对Component实例进行评估。并且也不需要单引号。像这样使用它:

<li *ngFor="let result of jsonList">
    <a (click)="updateId(result.id, result.name)">{{result.name}}</a>
</li>

答案 1 :(得分:1)

在指定事件处理程序的参数(ng-click)时,您不需要{{}}。正确的语法是

<li *ngFor="let result of jsonList">
    <a (click)="updateId(result.id, result.name)">{{result.name}}</a>
</li>