0

So I will do something like this often

save(...keys: string[]) {
    keys.foreach(x => // save);
}

I can call this any of these ways because of the spread operator.

save('string1', 'string2');
save(['string1', 'string2']);
save('string');

I love this behavior but what I have a case where I have an @input on a component that I want to behave the same way. sometimes I want to just give it one item, other times I want to give it an array. How could this syntax be applied? I want to be able to do something like this.

@Input() ...myClass: ClassBase[] = [];

And usages like this.

// ts
currentClass = new ClassBase();
conflictingClasses = [new ClassBase(), new ClassBase()];

// html
<my-component [myClass]="currentClass"></my-component>
<my-component [myClass]="conflictingClasses"></my-component>

How can I get this kind of behavior? We already use this component in several places but we only give it one item, I would like to not have to mass refactor to change this component to take an array of items.

thanks!

1 Answer 1

2

I can call this any of these ways because of the spread operator.

No, the premise of your question is wrong. You must call it with n number of string arguments. A string array string[] is not the same thing. This is shown below:

function save(...keys: string[]) {
    keys.forEach(x => /** save */);
}


save('string1', 'string2'); // OKAY
save('string'); // OKAY 
save(['string1', 'string2']); // ERROR !

Please as a different question instead of editing this as it will probably not get much attention after edits 🌹. PS: have fun and stay happy!

Sign up to request clarification or add additional context in comments.

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.