0

I have an Angular2 project in which I am trying to construct an object with an unknown number of parameters from an HTML button click which calls a function. This function is using rest parameters in order to accept an unknown number of parameters as shown below:

addArguments(...args: any[]) {
    for (var i = 0, arg; arg = args[i]; i++) {
        console.log("add values args:", ...arg);
    }
}

This function is called from an HTML button class as below:

<button type="submit" class="btn" (click)="addArguments(6, 'Argument1', 'Argument2')">
     Add
</button>

The problem is, when I run this code, the console output is add values args: 6.

I cannot figure out why it is not passing through the additional 'Argument1' and 'Argument2'.

2
  • I don't know what you meant to do with that for loop but here's a working plunker:plnkr.co/edit/mj1xNPJU1rwFQVZHZIaM?p=preview Commented Jan 12, 2017 at 18:49
  • Found the issue was passing in ...args versus args in a subsequent function call. ...args must be used to continue to pass the separated parameters to another function which also accepts ...args. Commented Jan 12, 2017 at 19:24

1 Answer 1

1

You're not constructing the for loop correctly.

Should be:

addArguments(...args: any[]){
    for (var i = 0, i < args.length; i++) {
        console.log("arg:", args[i]);
    }

    console.log("args:", args); // [6, "Argument1", "Argument2"]
}
Sign up to request clarification or add additional context in comments.

1 Comment

The construction is not incorrect. This assigns and the argument in the loop. I found the issue was passing of args instead of ...args.

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.