簡體   English   中英

單擊清除角材料自動完成

[英]Clear Angular Material autocomplete on click

嗨,我想在單擊時重置角度材料自動完成的值,但我不知道該怎么做。

我的代碼:

  <mat-form-field>
        <input type="text" placeholder="Give Rights" formControlName="selectedOption" aria-label="User" matInput  [matAutocomplete]="auto" (input)="onSearchChange($event.target.value)">
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let user of users" [value]="user.displayName" (onSelectionChange)="setSelectedUser($event, user)">
                {{ user.displayName }}
            </mat-option>
        </mat-autocomplete>
        <button (click)="resetValue($event)">RESET</button>
    </mat-form-field>

TS :

    this.nameForm = this._formBuilder.group({
    selectedOption: new FormControl()
});    

    resetValue(){
    console.log("Value -> ", this.nameForm.value.selectedOption);
    this.nameForm.value.selectedOption = "test";
}

你能幫助我嗎 ?

首先,您需要獲取要設置其值的控件的句柄,您可以使用 FormGroup 的 get 方法執行此操作

nameForm.get('selectedOption')

然后你可以簡單地調用 Reactive Forms 提供的 setValue 方法來設置該控件的值。

<button (click)="nameForm.get('selectedOption').setValue('')">RESET</button>

您可以使用雙向數據綁定將輸入值綁定到類的屬性,並使用resetValue對該屬性進行操作。


<input [(ngModel)]="selectedOption" ...

resetValue() {
  this.selectedOption = '';
}

請參閱此處的工作示例

對我有用的是添加對輸入控件的本地引用,並使用它在單擊選項時將值設置為空:

input
    #matInput
    type="text"
    placeholder="Search"
    aria-label="Search"
    matInput
    [formControl]="search"
    [matAutocomplete]="auto">
  <mat-autocomplete
    #auto="matAutocomplete"
    (optionSelected)="onOptionSelected($event)"
    panelWidth="auto">
    <mat-option *ngFor="let item of items | async"
      [value]="item.Key"
      (click)="matInput.value=''">
      {{ item.Name }}
    </mat-option>
  </mat-autocomplete>

你的語法看起來不對。 試試this.nameForm.controls['selectedOption'].setValue('test');

 <pre> //html <input #inputSearch ........> <button (click)="btnClick()" ..........>click</button //ts import {ElementRef, ViewChild} from '@angular/core'; @ViewChild('inputSearch') inputSearch: any; constructor(private elementRef: ElementRef,.............) { this.inputSearch = elementRef } btnClick(){ this.inputSearch.nativeElement.value=null; this.inputSearch.nativeElement.dispatchEvent(new Event('input', { })) } </pre>

對於那些使用反應式表單的人,可以使用下面的來清除輸入。

//import Formbuilder in contructor
constructor(
    private fb: FormBuilder
  ) {}

public form_details : FormGroup;

//Define the form names on ngOnInit
ngOnInit(): void {
    this.form_details = this.fb.group({
      payment_type: ['', Validators.required],
      payment_date: [new Date(), Validators.required],
      total_amount: [
        { value: 0, disabled: false },
        [
          Validators.required,
          Validators.min(1)
        ],
      ],
      remarks: [''],
    });
}

// Then add mat-autocomplete inside form in template

<form [formGroup]="form_details" (submit)="onSubmit()">


          <mat-form-field appearance="fill" class="example-full-width">
            <mat-label>Payment type </mat-label>
            <input
              type="text"
              placeholder="Pick one"
              matInput
              formControlName="payment_type"
              [matAutocomplete]="auto"
            />
            <mat-autocomplete
              #auto="matAutocomplete"
              [displayWith]="paymentTypeDisplayFn"
              (optionSelected)="onPaymentTypeChange($event)"
            >
              <mat-option
                *ngFor="let option of filteredPaymentTypes | async"
                [value]="option"
              >
                <small
                  ><b>{{ option.payment_code}}</b></small
                >
                / <small>{{ option.payment_type_name}}</small>
              </mat-option>
            </mat-autocomplete>
            <button
              *ngIf="form_details.get('payment_type').value"
              matSuffix
              mat-icon-button
              aria-label="Clear"
              (click)="handleClearInput('customer')"
            >
              <mat-icon>close</mat-icon>
            </button>
          </mat-form-field>

</form>


// Add the following code in component

paymentTypeDisplayFn = (options) => {
    return options && options.payment_type_name
      ? options.payment_type_name+ '/' + options.payment_code
      : '';
  };

  private _filteredPaymentType(value: any): any[] {
    const filterValue = value.toLowerCase();
    return this.options.filter(
      (option) =>
        option.payment_code.toLowerCase().includes(filterValue) ||
        option.payment_type_name.toLowerCase().includes(filterValue)
    );
  }

  onPaymentTypeChange(e) {
    // handle your own logic
  }

 handleClearInput(key) {
    this.payment_entry_details.patchValue({
      [key]: '',
    });
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM