将Angular组件绑定到特定类型

时间:2017-06-06 11:04:53

标签: angular typescript

我目前正在使用Angular和TypeScript,我想知道是否可以绑定组件@Input以使用特定类型?

示例

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

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

绑定组件时,foobar都是string。 angular是否提供了强制指定类型的方法?

我试过这个,但我不喜欢它...... (看起来很脏而且不太优雅)

@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';
    }
}

如果Angular的输入中有某些内容可以充当绑定委托,那就太好了;例如:

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

2 个答案:

答案 0 :(得分:2)

如果使用类似fuu="123"的绑定,则值始终为字符串。但如果你像这样绑定:

[fuu]="123" 

该值的类型为数字。 这意味着,值的处理方式与普通的JS一样:

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

答案 1 :(得分:2)

写作时

foo="123"

您使用 one-time string initialization 。 Angular将值设置为foo属性为字符串并忘记它。

如果您想使用字符串以外的其他内容,请使用括号

[foo]="123"

编写绑定时,请注意模板语句的执行上下文。模板语句中的标识符属于特定的上下文对象,通常是控制模板的Angular组件。

使用属性绑定时,值将按原样传递

[foo]="isValid"

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

如果你想要枚举,那么你应该写这样的东西

[foo]="MyEnum"

...

enum MyEnum {
  one,
  two,
  three
}

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

其他例子

[foo]="445" => number
[foo]="'445'" => string
[foo]="x" => typeof x or undefined