Matthew Layton
Matthew Layton

Reputation: 42380

Binding Angular component with specific type

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;

Upvotes: 2

Views: 1171

Answers (2)

yurzui
yurzui

Reputation: 214295

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

Upvotes: 3

Dinistro
Dinistro

Reputation: 5730

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

Upvotes: 2

Related Questions