【问题标题】:Binding Angular component with specific type将 Angular 组件与特定类型绑定
【发布时间】:2018-04-24 02:17:50
【问题描述】:

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

示例

@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 中有一些东西可以充当绑定委托,那就太好了;例如:

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

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    当你写作时

    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
    

    【讨论】:

      【解决方案2】:

      如果您使用fuu="123" 之类的绑定,则该值将始终为字符串。但是如果你这样绑定:

      [fuu]="123" 
      

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

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

      【讨论】:

      • 当我想使用非内置类型(如 typescript 枚举)时会发生什么?
      • @series0ne 我认为,只有在绑定另一个组件的属性时才有效,否则无效。
      • @series0ne 这应该不是问题。我还没有测试过,但如果你在组件中导入(或声明)枚举,你应该可以在模板中使用它。
      猜你喜欢
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 2017-05-16
      • 1970-01-01
      • 2017-06-09
      相关资源
      最近更新 更多