【问题标题】:Match @Input() with a defined list in Angular将 @Input() 与 Angular 中定义的列表匹配
【发布时间】:2018-01-08 12:21:39
【问题描述】:

检查用户输入是否在条目白名单中的最佳做法是什么?

export class myClass {
  @Input() type: string;
}

设置type 应该只有在它在一个定义的列表中时才可能,否则它应该是空的。有角度或打字稿的常用方法吗?

【问题讨论】:

  • 使用私有属性来存储经过验证的输入。并查看 getter 和 setter 以验证您的输入。

标签: angular validation typescript input


【解决方案1】:

@Input 使用私有实例字段和getter/setter 的组合。像这样:

export class myClass {
    private validType: string;

    @Input()
    public set type(value: string) {
       if(this.validate(value)) {
          this.validType = type;
       } else {
          this.validType = '';
       }
    }

    public get type() {
       return this.validType;
    }

    private validate(value: string) {
       // do your validation here
       return true;
    }
}

这确保每次输入属性更改时,都会检查我的验证方法(我使用validate 作为此示例的名称)。如果您使用 type 属性,您将始终获得经过验证的属性validType

如果您正在处理表单输入,您应该明确地为此类任务定义自己的 validator 并将其应用于表单字段。

【讨论】:

    猜你喜欢
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    相关资源
    最近更新 更多