2

Working my own custom component and stuck with how to make it use both attributes and variables. I'm using @Input attribute directives and this works when I pass in correctly scoped variables.

component (this works)

<mycomp [arrayValue]= "someArrayVar">html</mycomp>

but I'm not sure what I need to do to make this work??

component (not working)

<mycomp arrayValue= "[1,2,3,4,5]">html</mycomp>

my directive looks something like this...

directive

    export class MyComp implements DoCheck, OnInit {

      @Input() arrayValue: number[];

Would appreciate anyone who can explain how I'd implement both input alias and attributes for passing in when no variable is used and a string is passed like "[1,2,3,4,5]"

1
  • Are you really expecting to hard code an array in the template? Commented Jul 24, 2017 at 23:00

2 Answers 2

4

What you want is similar to your first version:

<mycomp [arrayValue]= "someArrayVar">html</mycomp>

Just use this:

<mycomp [arrayValue]= "[1,2,3,4,5]">html</mycomp>

That is keep the brackets around your directive name in order to instruct angular to treat the value as expression.

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

Comments

0

arrayValue="[1,2,3,4,5]" will pass the value you give it as a string. If you really want to make it possible to pass the array this way, you'll have to parse it yourself (for example, using JSON.parse), probably in the setter (not getter) for arrayValue.

@Input() set arrayValue(value: string | number[]) {
  if (typeof value == 'string') {
    this._arrayValue = JSON.parse(value)
  } else {
    this._arrayValue = value
  }
}

But the question is, why you want to do this? It's not recommended.

1 Comment

-1 granted this answer provides a solution to the OPs problem, however the solution implements functionality that angular already has built-in. And I feel this answer is misleading on how to address this kinds of problems and it should in no way be the accepted answer IMHO, hence -1.

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.