繁体   English   中英

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

[英]Angular2 - pass dynamically loaded parameters to function while doing dropdown value selection

请检查是否以正确的格式传递了updateId方法的li标签点击函数的参数? 控制台中的错误仅显示该行。

我的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传递动态参数。 因此,请帮助我获得解决方案。

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

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

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

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

暂无
暂无

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

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