如果我在第一个输入字段中传递“匹配的”字符串值,如何禁用其他输入字段

时间:2018-08-31 10:42:14

标签: angular forms

我正在使用模板驱动的表单,并且如果其他输入字段与我输入的字符串匹配,则需要禁用其他输入字段。 例如第一个输入值,如果它是=“ sample”,则其他输入应被禁用。

for k, v in foo.items():
    bar(k, v)

请告诉我如何实现此目标,我正在尝试使用“禁用”功能,但我不知道该如何实现。

1 个答案:

答案 0 :(得分:0)

我认为将模板变量放在这些输入(#sample#sample1)上并为其分配ngModel在您已经使用[(ngModel)]时是多余的。您将在属性samplesample1中获得所有内容。因此,您可以摆脱这些模板变量#sample#sample1

但是,当您填写sample的值然后将其清空时,仅执行此操作将无效。在这种情况下,第二个输入仍将被禁用。

似乎是Angular的错误。不确定。解决方法是,可以在组件类中添加另一个属性,该属性记录samplesample1的更改后的值,然后禁用/启用sample1文本字段。方法如下:

模板:

<input 
  type="text" 
  name="sample" 
  [(ngModel)]="sample"
  required="true"
  (change)="shouldBeDisabled()" />

<br><br>

<input 
  type="text" 
  name="sample1" 
  [(ngModel)]="sample1"
  required="true" 
  (change)="shouldBeDisabled()"
  [disabled]="shouldInputBeDisabled" />

组件类:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  sample;
  sample1;
  shouldInputBeDisabled;

  shouldBeDisabled() {
    this.shouldInputBeDisabled = this.sample !== '' && this.sample === this.sample1;
  }

}

这里是Sample StackBlitz

此外,由于还需要以下输入,因此如果提交按钮上存在验证,您可能无法提交表单。在这种情况下,做有需要的人。