首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ngFor中映射方法参数,方法也包含在每个元素的数组中

如何在ngFor中映射方法参数,方法也包含在每个元素的数组中
EN

Stack Overflow用户
提问于 2022-08-10 17:16:23
回答 1查看 36关注 0票数 0
代码语言:javascript
复制
  <ng-container *ngFor="let btn of btns">
    <button class="btn me-4 {{btn.class}}" [title]="btn.title" #btn (click)="btn.functionToCall(btn,'hello')">
      {{btn.name}}
    </button>
  </ng-container>

我正在循环按钮数组,并在按钮数据中传递方法it self。

代码语言:javascript
复制
    import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  PrintFour() {
    console.log("four");
  }
  PrintThree() {
    console.log("three");

  }
  PrintTwo() {
    console.log("two");

  }
  PrintHello(data?: string) {
    console.log("hello is printed");
    if (data)
      console.log(data);
  }

  printParamert1(btn: HTMLButtonElement) {
    btn.innerHTML = "1 is clicked"
  }

  printParamert2(btn: HTMLButtonElement) {
    btn.innerHTML = "2 is clicked"
  }
  btns: Array<any> = [

    { "name": "one", "title": "one", "functionToCall": this.PrintHello, "class": "btn-success" },
    { "name": "two", "title": "two", "functionToCall": this.PrintTwo, "class": "btn-danger" },
    { "name": "three", "title": "three", "functionToCall": this.PrintThree, "class": "btn-info" },
    { "name": "four", "title": "four", "functionToCall": this.PrintFour, "class": "btn-secondary" },
    { "name": "five", "title": "five", "functionToCall": this.printParamert1, "class": "btn-secondary" },
    { "name": "six", "title": "siz", "functionToCall": this.printParamert2, "class": "btn-secondary" },


  ]
}

这里我很困惑,有些方法包含了不同类型的参数,并且我使用两个参数来调用它,我认为它会调用,但不会调用。

我还创建了stackblit示例:https://stackblitz.com/edit/angular-ivy-8dsrxy?file=src/app/app.component.ts

我只想知道如何将参数传递给适当的方法。

EN

回答 1

Stack Overflow用户

发布于 2022-08-10 18:25:52

我认为您这样做是正确的,问题是您使用的是相同的变量名,所以它并没有真正选择html元素。只需给出一个不同的模板变量名,它就可以工作了。

代码语言:javascript
复制
<button class="btn me-4 {{btn.class}}" [title]="btn.title" #btnElement (click)="btn.functionToCall(btnElement ,'hello')">
  {{btn.name}}
</button>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73310308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档