【问题标题】:angular change variable after filling all inputs填充所有输入后的角度变化变量
【发布时间】:2019-10-04 07:34:25
【问题描述】:

我在模板中有几个输入

<input type="text" class="form-control" name="name" id="name" placeholder="name" title="nanme">
<input type="text" class="form-control" name="surname" id="name" placeholder="surname" title="surname">

在 ts 文件中我有变量 testVar=false;

我想要testVar=true 在两个输入都被填充(不是空的)之后。我该怎么做?

【问题讨论】:

    标签: angular variables input


    【解决方案1】:

    你可以这样使用Reactive Forms

    模板:

    <div [formGroup]="profileForm">
          <input formControlName="name" type="text" class="form-control" name="name" id="name" placeholder="name" title="nanme">
          <input formControlName="surname" type="text" class="form-control" name="surname" id="name" placeholder="surname" title="surname">
         <p>
            {{profileForm.status}}
        </p>
    </div>
    

    组件:

    import {Validators, FormBuilder} from '@angular/forms';
    profileForm = this.fb.group({
        name: ['', Validators.required],
        surname: ['', Validators.required]
    });
    constructor(private fb: FormBuilder) { }
    

    您可以使用profileForm.valid,而不是使用testVar

    【讨论】:

      【解决方案2】:

      您可以在此处使用本地引用#input1 和 #input2 并使用 keydown.enter

      <input type="text" class="form-control" name="name" id="name" placeholder="name" title="nanme" #input1 (keydown.enter)="checkInputs(input1.value,input2.value)">
      <input type="text" class="form-control" name="surname" id="name" placeholder="surname" title="surname" #input2 (keydown.enter)="checkInputs(input1.value,input2.value)">
      

      然后在 .ts 文件中:

      checkInputs(input1,input2) {
        if(input1.length && input2.length){
        this.testVar=true;
        }else{
        this.testVar=false;
       }
      }
      

      【讨论】:

        【解决方案3】:

        试试这样:

        模板:

        <input type="text" class="form-control" name="name" id="name" placeholder="name" title="nanme" [(ngModel)]="details.name" (ngModelChange)="checkTestValue()">
        <input type="text" class="form-control" name="surname" id="name" placeholder="surname" title="surname" [(ngModel)]="details.surname" (ngModelChange)="checkTestValue()">
        

        TS:

         details: any = {};
        
          checkTestValue() {
            if (this.details.name && this.details.surname) {
              this.testVar = true;
            } else {
              this.testVar = false;
            }
          }
        

        Working Demo

        【讨论】:

        • 用户在问题中提到模板有多个输入,而不仅仅是两个。也不一定所有输入值都可以属于一个变量对象,在您的情况下是“详细信息”。
        • @Hemendra 在这种情况下他可以使用Object.keys()
        猜你喜欢
        • 1970-01-01
        • 2018-11-24
        • 1970-01-01
        • 2017-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多