【问题标题】:how to disable other input field if I get "matched" string value I'm passing in 1st input field Angular如果我在第一个输入字段Angular中传递“匹配”字符串值,如何禁用其他输入字段
【发布时间】:2018-08-31 10:42:13
【问题描述】:

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

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

<input 
  type="text" 
  name="sample1" 
  [(ngModel)]="sample1" 
  #sample1=ngModel 
  required="true" 
  [disabled]="sample.value==sample" />

请告诉我如何实现这一点,我正在尝试使用禁用,但我不明白如何做到这一点。

【问题讨论】:

    标签: angular forms


    【解决方案1】:

    我认为在这些输入(#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

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

    【讨论】:

    • 谢谢@Siddharth...但我想检查第一个输入值然后需要禁用。
    • 尝试更新的答案。它将首先检查是否定义了sample
    • 不..它不起作用,您的解决方案将如何获取第一个输入值并进行比较??
    • 非常感谢@Siddharth 抽出宝贵时间,但您的第一个答案是正确的,很抱歉我犯了一个愚蠢的错误,请用您的第一个答案再次更新,我会做到的作为正确答案。
    • 我在第一个输入字段中输入并删除的任何内容,因此第二个输入字段被禁用。
    猜你喜欢
    • 2019-01-19
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2014-10-31
    • 1970-01-01
    • 2019-07-20
    相关资源
    最近更新 更多