<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。
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
我只想知道如何将参数传递给适当的方法。
发布于 2022-08-10 18:25:52
我认为您这样做是正确的,问题是您使用的是相同的变量名,所以它并没有真正选择html元素。只需给出一个不同的模板变量名,它就可以工作了。
<button class="btn me-4 {{btn.class}}" [title]="btn.title" #btnElement (click)="btn.functionToCall(btnElement ,'hello')">
{{btn.name}}
</button>https://stackoverflow.com/questions/73310308
复制相似问题