【问题标题】:How to hide a input field according to the value of selection in angular?如何根据角度选择的值隐藏输入字段?
【发布时间】:2019-04-05 13:33:25
【问题描述】:

我有三个输入字段:

首先加载页面时会显示所有三个字段,但是当我选择 value1 时,应显示地址字段并隐藏电话号码。同样,当点击 value2 时,电话号码被显示,地址被隐藏。

 <div class="form-group col-md-3">
               <label for="age">Address</label>
               <input type="text"
                id="address" 
                class="form-control" 
                name="address"
                placeholder="Enter the address" 
                [(ngModel)]="selection.address" 
                #address="ngModel"
                 [ngClass]="{ 'is-invalid': f.submitted && selectionDate.invalid }"
                 required 
                 />
                 <div *ngIf="f.submitted && address.invalid" class="invalid-input">
            <!-- individual validation errors -->
            <div *ngIf="address.errors?.required">Address is required</div>
          </div>
            </div>

            <div class="form-group col-md-3">
               <label for="age">Phone Number</label>
               <input type="text" 
               id="phoneNumber"
                class="form-control" 
                name="phoneNumber"
                placeholder="Enter the Phone number" 
                [(ngModel)]="selection.phoneNumber" 
                #phoneNumber="ngModel" 
                [ngClass]="{ 'is-invalid': f.submitted && phoneNumber.invalid }"
                 required />
                  <div *ngIf="f.submitted && phoneNumber.invalid" class="invalid-input">
            <!-- individual validation errors -->
            <div *ngIf="phoneNumber.errors?.required">Phone Number is required</div>
          </div>
            </div>
         </div>
         <!--row 3-->
         <div class="col-md-12">
            <div class="form-group col-md-3">
               <label for="selectionType">Selection Type</label>
               <select class="form-control" id="selectionType" 
                [(ngModel)]="selection.selectionType" name="selectionType"  required  #selectionType="ngModel"  [ngClass]="{ 'is-invalid': f.submitted && selectionType.invalid }">
               <option value="value1">Value1</option>
               <option value="value2">Value2</option>
               </select>
               <div *ngIf="f.submitted && selectionType.invalid" class="invalid-input">
            <!-- individual validation errors -->
            <div *ngIf="selectionType.errors?.required">Selection Type is required</div>
          </div>
            </div>

在上面的原始代码中,我尝试进行如下更改:

<option value="value1" (click)="callme()">Value1</option>

这是在 selection.component.ts 文件中。我还尝试打印到控制台并尝试输出我的逻辑,但我没有看到任何变化。

callme(){
    console.log("call me");
}

我怎样才能做到这一点?有新的方法吗?

【问题讨论】:

  • 尝试使用(更改)而不是点击“选择”而不是点击选项

标签: javascript angular typescript select angular6


【解决方案1】:

使用 change evet 绑定和 boolena 来跟踪更改:

参考: https://stackblitz.com/edit/angular-qihhhh?file=src%2Fapp%2Fapp.component.html

app.component.html

<form action="javascript:;">
  <div class="form-group" *ngIf="isNameSelected">
    <label for="name">name :</label>
    <input type="text" class="form-control" id="name">
  </div>

  <br>

  <div class="form-group" *ngIf="!isNameSelected">
    <label for="address">address:</label>
    <input type="text" class="form-control" id="address">
  </div>
  <br/>

 <select (change)="selectInput($event)">
  <option value="Value-1">Value-1</option>
  <option value="Value-2">Value-2</option>
</select>

</form>

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  isNameSelected: boolean;
  selectInput(event) {
    let selected = event.target.value;
    if (selected == "Value-1") {
      this.isNameSelected = true;
    } else {
      this.isNameSelected = false;
    }
  }
}

【讨论】:

    【解决方案2】:

    您应该将事件添加到选择标签上

    <select (change)="callme($event)"></select>
    

    然后在你的组件中你可以创建一个方法如下

    callme(event): void {
        const selectedValue = event.target.value;
        console.log(selectedValue);
    }
    

    您还需要为地址和电话号码的外部 div 添加一个条件 *ngIf 以显示所选的一个

    我在这里为您创建了一个示例:https://stackblitz.com/edit/angular-rpxt4o?embed=1&file=src/app/app.component.ts

    【讨论】:

    • 如何隐藏任何输入字段?
    • @rrd 您需要将 *ngIf 添加到每个外部 div 上,以便有条件地显示/隐藏,然后在您的 callme 方法中,您将在组件中设置一个全局变量
    • @ashwinkarki 我添加了一个示例,说明如何在 stackblitz 上做你想做的事情
    【解决方案3】:

    组件:

    @ViewChild('address', {read: ElementRef}) address: ElementRef;
    @ViewChild('phoneNumber', {read: ElementRef}) phoneno: ElementRef;
    
    callme(event): void {
        const selectedValue = event.target.value;
        if(selectedValue === 'value1'){
          this.address.nativeElement.style.display = 'none';
          this.phoneno.nativeElement.style.display = 'block';
    
        else if(selectedValue === 'value2'){
          this.phoneno.nativeElement.style.display = 'none';
          this.address.nativeElement.style.display = 'block';
    
        }
    }
    

    【讨论】:

      【解决方案4】:

      select标签内使用(change)="callme()",以便在所选选项的每次更改时触发。

      <select #sel (change)="callme($event, sel.value)">
      
      </select>
      

      使用此模板变量隐藏/显示每个字段:

      <input *ngIf="sel.value === 'value1'">
      

      修改您的代码以满足您的确切需求。

      【讨论】:

      • 如何隐藏任何输入字段?
      【解决方案5】:

      在我的情况下,我需要隐藏多个表单字段取决于多种类型,所以我所做的是,

      1. 已创建包含所有表单字段的类
      export class FormFields {
      
            public jobTitle: boolean ;
            public opportunityType: boolean ;
            public industry: boolean ;
            public jobType: boolean ;
            public jobTags: boolean;
            
           }
      
      1. 创建了函数来隐藏提供的对象中的字段
      changeFieldVisibilityOnType(formObject, listOfFields) {
          for (let [key, value] of Object.entries(formObject)) {
            formObject[key] = listOfFields.includes(key) ? false : true;
          }
        }
      

      3.进入 HTML 表单处理更改事件。

      <select class="form-control " name="Type" [(ngModel)]="model.Type"
                                                      (change)="onChange($event)">
                                                      <option data-display="Type">Select Type</option>
                                                      <option [value]="jType.key"
                                                          *ngFor="let jType of masters.Types">{{jType.value}}
                                                      </option>
      
      1. 最后进入 onChange() 函数,将隐藏所需字段的对象和数组传递给 changeFieldVisibilityOnType 函数。
      onChange(event) {
          switch (event.target.value) {
            case 'JOB':
              var listOfFields = ["industry", "jobType"];
              this.changeFieldVisibilityOnType(this.objFormFields, listOfFields);
              break;
            case 'PAID_INTERN':
              listOfFields = ["jobType"];
              this.changeFieldVisibilityOnType(this.objFormFields, listOfFields);
            break;
          
          }
        }
      

      希望这会对某人有所帮助。祝你好运!!

      【讨论】:

        猜你喜欢
        • 2022-01-18
        • 1970-01-01
        • 2023-03-22
        • 2021-10-01
        • 2013-07-11
        • 2019-11-07
        • 1970-01-01
        • 2020-04-12
        • 2012-06-15
        相关资源
        最近更新 更多