2

I have a function from a library which is called like this:

example: setMode(CLR.Drop);

There are other options, 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.

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?

2
  • put CLR in a property of component (e.g. CLR = CLR) then your original code will work Commented Jun 18, 2020 at 10:58
  • HTML : <button (click)="selectMode('Drop')">Set Mode</button> TS : selectMode(mode) { if (mode == 'Drop') { mode = CLR.Drop; } else if (mode == 'Grab') { mode = CLR.Grab; } else if (mode == 'None') { mode = CLR.None; } setMode(mode); } Commented Jun 18, 2020 at 11:01

2 Answers 2

1

You could assign the property CLR to a local variable and pass it to the handler.

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'. String literal comparisons are case sensitive.

<button (click)="selectMode('Drop')">Set Mode</button>
Sign up to request clarification or add additional context in comments.

1 Comment

IDK, but giving type any just ruins the taste of TS. :/
0

Give the type of the parameter as the name of the member of the class. And assign the function to some method named variable. 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.