简体   繁体   English

在 angular 中的垫子自动完成值 select 之后禁用输入字段?

[英]Disable input field after select the value in mat autocomplete in angular?

Hi every i want to disable the input field after selected the value in drop down, and i want to reset the selected value using of reset button.大家好,我想在下拉列表中选择值后禁用输入字段,并且我想使用重置按钮重置选定的值。

For reference Stackblitz: https://stackblitz.com/edit/mat-autocomplete-1uelcd?file=app%2Fautocomplete-display-example.html供参考 Stackblitz: https://stackblitz.com/edit/mat-autocomplete-1uelcd?file=app%2Fautocomplete-display-example.html

For example:- If we selected any value in the input field then filed should be disabled after clicks the reset button it should enabled to select the value please check and help us.例如:- 如果我们在输入字段中选择了任何值,那么在单击重置按钮后应该禁用字段,它应该启用 select 该值请检查并帮助我们。

Html: Html:

    <div class="example-form">
      
      <form>
        <mat-form-field class="example-full-width">
          <input type="text" placeholder="Assignee" aria-label="Assignee" matInput [formControl]="myControl" [matAutocomplete]="auto2">
          <mat-autocomplete #auto2="matAutocomplete" [displayWith]="displayFn">
            <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
              {{ option.name }}
            </mat-option>
          </mat-autocomplete>
        </mat-form-field>
         <button  mat-raised-button (click)="onResetSelection()" color="primary">Reset Selection</button>
      </form>
     
    </div>

Reset:重置:


onResetSelection() {
    this.filteredOptions = [];
}

Disable:禁用:

[disabled]="filteredOptions =='option'"

You can do that with below approach你可以用下面的方法做到这一点

Add on select event to disable form control and while doing reset event just clear the form control.添加 select 事件以禁用表单控件,并在执行重置事件时清除表单控件。

In View:在视图中:

  <mat-autocomplete #auto2="matAutocomplete" (optionSelected)="onSelectionChanged($event)" [displayWith]="displayFn">
        <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
           {{ option.name }}
        </mat-option>
   </mat-autocomplete>

In Template:在模板中:

  ...

  onSelectionChanged(event: any) {
     this.formGroupName.controls['myControl'].disable();
  }

  onResetSelection() {
    // you can enable the control with below line
    this.formGroupName.controls['myControl'].enable();
    this.formGroupName.controls['myControl'].setValue('');
  }

  ...

Happy Coding.. :)快乐编码.. :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM