我想獲得自動完成顯示對象的一個參數,但保存另一個,迄今它似乎並沒有表現。值不顯示材質2自動完成
代碼是按材料2自動完成網站:Autocomplete
不同的是,[值]我要救「option.Id」而不是「選項」。
錯誤是當它記錄選項時,它實際上並沒有在輸入字段中顯示該值(使其保留空白)。
我-comp.html
<md-input-container>
<input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
<md-option *ngFor="let option of filteredOptions | async" [value]="option.Id">
{{ option.name }}
</md-option>
</md-autocomplete>
我-comp.ts
class MyComp implements OnInit {
myControl = new FormControl();
options = [
new User('Mary', 1),
new User('Shelley', 2),
new User('Igor', 3)
];
filteredOptions: Observable<User[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.startWith(null)
.map(user => user && typeof user === 'object' ? user.name : user)
.map(name => name ? this.filter(name) : this.options.slice());
}
filter(name: string): User[] {
return this.options.filter(option => new RegExp(`^${name}`, 'gi').test(option.name));
}
displayFn(user: User): string {
return user ? user.name : user;
}
}
class User {
name: string;
id: number;
constructor(name: string, id: number)
this.name = name;
this.id = id;
}
嘗試'[ngValue]' – SrAxi
可能導致問題的一件小事。在ngfor循環中使用'id'而不是'id'。 –
ngValue拋出模板解析錯誤,因爲它不是md-options的一部分。 Id正在被正確設置,值不被顯示。 – Aeseir