简体   繁体   English

Angular 添加 class 方法作为参数

[英]Angular add class method as parameter

I have a function from a library which is called like this:我有一个来自库的 function,它的名称如下:

example: setMode(CLR.Drop);

There are other options, Drop, Grab, None还有其他选项,Drop,Grab,None

So, I've created a method:所以,我创建了一个方法:

selectMode(mode) {
    setMode(mode);
}

On a button click I've tried this:在一个按钮点击我试过这个:

<button (click)="CLR.Drop">Set Mode</button>

When I do the above I get that CLR.Drop is undefined.当我执行上述操作时,我发现 CLR.Drop 是未定义的。

So, I've having to pass a number or string like this:所以,我必须像这样传递一个数字或字符串:

<button (click)="selectMode('drop')">Set Mode</button>

And this have to do this:这必须这样做:

selectMode(mode) {
    if (mode === 'Drop') {
        mode = CLR.Drop;
    } else if (mode === 'Grab') {
        mode = CLR.Grab;
    } else if (mode === 'None') {
        mode = CLR.None;
    }
    setMode(mode);
}

Is there a way to do this without end with lots of if's or a switch or is this the only way?有没有办法通过大量的 if 或 switch 无止境地做到这一点,或者这是唯一的方法?

You could assign the property CLR to a local variable and pass it to the handler.您可以将属性CLR分配给局部变量并将其传递给处理程序。

export class AppComponent {
  public clr = CLR;

  onClick(mode: any) {
    setMode(mode);
  }
}

Template模板

<button (mouseup)="onClick(clr.Drop)">Drop mode</button>

Or in the switch-case variant, send 'Drop' instead of 'drop' .或者在 switch-case 变体中,发送'Drop'而不是'drop' String literal comparisons are case sensitive.字符串文字比较区分大小写。

<button (click)="selectMode('Drop')">Set Mode</button>

Give the type of the parameter as the name of the member of the class.将参数的类型作为 class 的成员的名称。 And assign the function to some method named variable.并将 function 分配给某个名为变量的方法。 And call the method/并调用方法/

class Calc {

  add() {
    console.log('I am add');
  }

  subtract() {
    console.log('I am subtract');
  }

}


function CalcCaller(fun: keyof Calc ) {
const method = (new Calc())[fun];
  method();
}

CalcCaller('add');

Playground Link 游乐场链接

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

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