简体   繁体   中英

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

Please check that, I am passing the parameters of li tag click function of updateId method in the correct format or not ? The errors in the console shows that line only....

My app.component.html code is

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

My app.component.ts is ,

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

}

It is not working. The error is on the li tag click function method passing the dynamic parameters from the jsonList . So pls help me to get resolve.

Don't use the handlebars {{ }} in event bindings such as the (click) attribute - they will be evaluated against the Component instance automatically. and the single quotes are not needed either. Use it like so:

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

You don't need {{ }} while specifying arguments to an event handlers (ng-click). The correct syntax would be

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

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