【发布时间】:2020-03-09 13:36:04
【问题描述】:
Angular 和 ts 新手,我非常感谢任何和所有帮助,并为一个业余问题道歉。
我无法将自动完成表单中的值存储到变量中,并且一直未定义。我无法弄清楚解决方案。我希望能够将选定的选项存储在一个变量中,以便稍后在其他函数中调用。
这是我的 HTML 组件
<mat-grid-list cols="1" rowHeight="50px">
<mat-grid-tile>
<h2>Search job postings:</h2>
<form>
<mat-form-field>
<input type="text" matInput [matAutocomplete]="auto" [formControl]="myControl" />
</mat-form-field>
<button (click)="onclick(option)" mat-raised-button color="primary">Search</button>
<mat-autocomplete role="input" #auto="matAutocomplete"
[displayWith]="displayFunc">
<mat-option *ngFor="let option of filterOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</form>
</mat-grid-tile>
下面是我的component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { FormControl } from "@angular/forms";
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
@Component({
selector: 'app-jobs',
templateUrl: './jobs.component.html',
styleUrls: ['./jobs.component.scss']
})
export class JobsComponent implements OnInit {
public jobs;
public options: string[] = [];
public myControl = new FormControl();
public filterOptions: Observable<string[]>;
public chosenJob = "";
constructor(private http: HttpClient) { }
ngOnInit() {
let res = this.http.get("myroutehere");
res.subscribe(data => {
this.saveData(data);
});
this.filterOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => (this._filter(value))
))
};
private _filter(value: string): string[] {
const filterVal = value.toLowerCase();
return this.options.filter(option =>
option.toLowerCase().includes(filterVal)
);
};
saveData(resp) {
this.jobs = resp.jobs
console.log(this.jobs)
this.saveJobTitles(this.jobs)
};
saveJobTitles(x) {
x.map(name => this.options.push(name.data.title))
console.log(this.options)
};
// Fills form out with a string instead of object
displayFunc(subj) {
return subj ? subj : undefined;
};
onclick(value) {
this.chosenJob = value
console.log(this.chosenJob);
console.log(value)
};
};
【问题讨论】:
-
在地图里面,你必须返回 this._filter(value)... 或者去掉它周围的 ()..
标签: angular typescript onclick angular-material