【问题标题】:Angular 8, trouble passing value through form (click)Angular 8,通过表单传递值时遇到问题(点击)
【发布时间】: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


【解决方案1】:

您的代码对我来说看起来不错,我将它复制到 stackblitz 中,它似乎可以工作。我看到的唯一问题是您在单击事件的提交按钮中将option 作为参数传递。该选项只会是单击事件,但与输入字段无关。您不会通过那里获得该字段的值。 您正在将输入分配给您正在创建的 FormControl 对象,因此您可以通过 this.myControl.value 访问它,它应该包含该字段的值。 您从未提及选项列表是否正常工作,但我认为它没有任何问题。

这里是 stackblitz 供参考:https://stackblitz.com/edit/material-select

您还对从请求中收到的内容进行了大量数据操作,并调用了多个函数。我认为可以使用 RxJS 对其进行简化,不过这是未经测试的代码:

ngOnInit() {
  let res = this.http.get("myroutehere")
    .pipe(
       map(resp => resp.jobs),
    )
    .subscribe(names => this.options = names.map(name => name.data.title));
  ...
};

你可以这样摆脱saveData和saveJobTitles。

【讨论】:

  • 感谢大卫的帮助!
  • 不客气!也许您可以投票并将其标记为解决方案? :P
  • 大卫!感谢您花时间帮助我。代替选项的“this,myControl.value”正是我一直在寻找并解决了我的问题。非常感谢它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多