【问题标题】:Enable Button when two strings match certain criteria Angular 7当两个字符串匹配某些条件Angular 7时启用按钮
【发布时间】:2019-02-01 02:39:26
【问题描述】:

我正在使用 Angular 7,并且希望在两个输入不符合指定条件时禁用按钮。

我有以下代码:

HTML:

<input type="text" pInputText [(ngModel)]="name" placeholder="placeholder"/>
<input type="text" pInputText [(ngModel)]="identifier" placeholder="identifier"/>

<button pButton type="button" class="ui-button-raised ui-button-rounded" label="Click me!" disabled="{{validateIdentifier() && name.length > 0}}"></button>

TS:

 private identifier: string = "";
 private name: string = "";

 validateIdentifier(): boolean {
    const REGEXP = new RegExp(/[EHIS]-[0-9]{9}/);
    return REGEXP.test(this.identifier);
}

因此,当我插入与以下正则表达式匹配的字符串时:(E|H|I|S)-[0-9]{9} 并且插入的 name-attribute 的长度至少为 1,我希望启用我的按钮,否则不启用。

遗憾的是,我的按钮在任何输入时都被(并保持)禁用。我做错了什么?

【问题讨论】:

  • 试试[disabled]="validateIdentifier() &amp;&amp; name.length &gt; 0"
  • 你能给出你想输入的字符串吗?

标签: regex angular typescript


【解决方案1】:

我认为你的布尔逻辑有一点错误。我认为您想否定validateIdentifier() 的结果,并说如果不是 vailidateIdentifier 或长度为 0,则禁用。例如

<button
  pButton
  type="button"
  class="ui-button-raised ui-button-rounded"
  label="Click me!"
  [disabled]="!validateIdentifier() || name.length === 0">
</button>

【讨论】:

  • 确实,你是对的,我有一个错误,因为我希望[disabled] 在条件匹配时成为false,以便启用按钮,好点!实际上,正如@ABOS 所说,我错过了disabled 周围的括号。感谢你们俩:) - 接受这个答案,因为你(含蓄地)陈述了两个错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 2021-12-02
  • 2015-08-24
  • 2022-01-17
  • 2020-10-04
相关资源
最近更新 更多