[英]prefill mat-autocomplete in angular 2 material 2
當我嘗試編輯記錄時,我無法設置mat-autocomplete
的值 我在FormBuilder
object 中使用自動完成作為FormControl
object 並設置從服務器接收到的值我正在使用Formbuilder.setValue()
方法,但這並沒有設置自動完成,盡管它向服務器發送了一個請求,因為我正在使用 Observables 的valueChanges
方法......任何幫助將不勝感激。
以下是我正在使用的代碼:
組件.ts
this.filteredData = this.addDetailsForm.get('product').valueChanges
.debounceTime(400)
.do(value =>
{
let exist = this.myContent.findIndex(t => t.text === value);
if (exist > -1) return;
this._dataService.getSwiftProducts(value)
.subscribe((res: any[]) => { this.myContent = res; });
}).delay(500).map(() => this.myContent);
組件.html
<div class="row">
<label class="col-lg-4 control-label">Product: </label>
<div class="col-lg-5">
<input type="text" class="form-control"
(keyup.enter)="chooseFirstOption()"
placeholder="Pick one" aria-label="Number"
matInput ="product" formControlName="product"
[matAutocomplete]="auto">
<p *ngIf="addDetailsForm.controls.product.errors">
This field is required!
</p>
<mat-autocomplete #auto="matAutocomplete"
[displayWith]="displayFn">
<mat-option *ngFor="let option of filteredData | async"
[value]="option">
{{ option.description }}
</mat-option>
</mat-autocomplete>
</div>
Angular、材料、操作系統、TypeScript 的版本:
Angular : "@angular/core": "^5.0.0",
Material : "@angular/material": "^5.0.0-rc0",
OS: Windows 7
Typescript : "typescript": "^2.6.2"
經過大量研究,甚至激怒了Angular Material的開發團隊,我意識到我在嘗試編輯記錄時發送的回復不正確。 我正在發送一個字符串作為自動完成的響應,而它應該是一個對象。 這實際上取決於displayFn
函數的編寫方式。 下面是我的displayFn function
displayFn(object): string {
console.log("Display Object is ---> " + object);
return object ? object.description : object;
}
所以我需要發送一個對象作為響應..我向可能會打擾的人致歉。
一旦您的表單加載,您就可以簡單地執行此操作。 您不應該需要所有這些超時。
this.formControls.get('controlName').setValue(option.value);
如果您的自動完成池值來自來自服務器或任何異步函數的數組,請確保您僅在該數組初始化后嘗試設置默認值。 例如,如果您從服務器獲取產品名稱列表,請等待產品列表初始化。 在此之前設置默認值不會持續。 它甚至可能會拋出更改檢測錯誤。
使用 formControl.patchValue() 或者如果這不起作用,請使用 viewChild 來選擇輸入元素並顯式設置 value 屬性。
@ViewChild('inputTempRef', {static: false}) myInput: ElementRef;
最后,當您的數組初始化時,請執行以下操作:
myInput.nativeElement.value = 'presetValue'
我遇到了同樣的問題,這段代碼幫助了我:
displayWithSector(sector: Setor): string {
return typeof sector !== 'string' ? sector.description : sector;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.