2

I'm currently working with Angular and TypeScript and I want to know if it's possible to bind component @Inputs to use specific types?

Example

@Component({selector: 'foobar'})
export class FooComponent {
    @Input() foo: number;
    @Input() bar: boolean;
}

<foobar foo="123" bar="true"></foobar>

When the component is bound, both foo and bar are string. Does angular provide a way to enforce the specified type?

I tried this, but I don't like it...(it seems dirty and not very elegant)

@Component({selector: 'foobar'})
export class FooComponent {
    foo: number;
    bar: boolean;

    @Input('foo') set _foo(value: string) {
        this.foo = Number(value);
    }

    @Input('bar') set _bar(value: string) {
        this.bar = value === 'true';
    }
}

It would be nice if there was something in Angular's Input that could act as a binding delegate; For example:

@Input('foo', (value: string) => Number(value)) foo: number = 123;

2 Answers 2

3

When you write

foo="123"

you use one-time string initialization. Angular sets value to foo property as string and forgets about it.

If you want to use something other than string then use the brackets

[foo]="123"

When writing a binding, be aware of a template statement's execution context. The identifiers in a template statement belong to a specific context object, usually the Angular component controlling the template.

When you use property binding then value is passes as it is

[foo]="isValid"

...
@Component({...})
class MyComponent {
  isValid: boolean = true;

if you want to have enum then you should write something like this

[foo]="MyEnum"

...

enum MyEnum {
  one,
  two,
  three
}

@Component({...})
class MyComponent {
  MyEnum = MyEnum;
}

Other examples

[foo]="445" => number
[foo]="'445'" => string
[foo]="x" => typeof x or undefined
Sign up to request clarification or add additional context in comments.

Comments

2

If you use a binding like fuu="123" the value will always be a string. But if you bind like this:

[fuu]="123" 

The value will be of type number. This means, that the values are treated like in normal JS:

[fuu]="true"   -> boolean
[fuu]="'true'" -> string
[fuu]="123"    -> number

3 Comments

What happens when I want to use a non-built-in type, like a typescript enum?
@series0ne That, I think, will only work if you bind a property of another component, otherwise not.
@series0ne This shouldn't be a problem. I haven't tested it but if you import (or declare) the enum in the component you should be able to use it in the template.

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.