【问题标题】:Patchform autocomplete material in typescript打字稿中的补丁形式自动完成材料
【发布时间】:2018-04-11 21:45:05
【问题描述】:

我有这个例子Demo

我试图在 City 中显示 Florida,但对我来说不起作用,我只能显示 3,city_id。为此,我使用了以下代码:

我有 2 个班级,客户和城市

  city: City[] = [
    {
      name: 'Arkansas',
      city_id: '1'
    },
    {
      name: 'California',
      city_id: '2'
    },
    {
      name: 'Florida',
      city_id: '3'
    },
    {
      name: 'Texas',
      city_id: '4'
    }
  ];
  client: Client[] = [
    {
      client_name: 'MyName',
      city_id: '3',
      email: 'myemail@gmail.com'
    }
  ];

我试图用这个函数在 html 中显示这个值:

  populateForm() {
      this.myform.patchValue({
      city_id: this.client.map(x => x.city_id),
      email: this.client.map(x => x.email),
      client_name: this.client.map(x => x.client_name)

    })
  }

email和client_name可以html显示,但是city_id没有。

我的html代码:

<form [formGroup]="myform">
    <input formControlName="client_name"  placeholder="name">
    <input formControlName="email"  placeholder="email" >
    <input formControlName="city_id" Input placeholder="City" aria-label="State" [matAutocomplete]="auto" [formControl]="cityy">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let item of filteredOptionsCity | async" [value]="item.name">
        <span>{{ item.name }}</span> 
      </mat-option>
    </mat-autocomplete>
  </form>

我的结果:

我要显示:

**`

client_name:MyName city_id:佛罗里达州电子邮件:myemail@gmail.com

`**

我在等待你的建议。

谢谢 编辑:

  client: Client;
      populateForm() {
        this.activatedRoute.params.subscribe(
          params => {
            this.ws.getClientById(params['id']).subscribe(
              client => {
                this.client = client;
                this.patchForm();
              }
            );
          }
        );
      }

      patchForm() {
        this.myform.controls['client_name'].setValue(this.client.clientName);
        this.editClientForm.controls['city_id'].setValue(this.client.city);
        this.editClientForm.controls['email'].setValue(this.client.email);
    }

类:

export class Client {
   clientName: string;
   email: string;
   city: City[];}

export class City {
  city_id: string;
  name: string;}

城市

    cityes: City[] = [];

    selectedCity: string;

 ngOnInit() {
    this.ws.getAllCity().subscribe(
      cityes => {
          this.cityes = cityes.map((city) => {
          return new City(city);
        });
          console.log(cityes) //return all my city
      }
    );

 this.selectedCity = this.cityes.filter(
      x => x.city_id === this.client.city
      .map(x => x.city_id)[0])
      .map(y => y.name).join('')
      console.log(this.cityes) //cityes is empty
     }

更新

  patchForm() {
    this.myform.controls['client_name'].setValue(this.client.clientName);
    this.editClientForm.controls['email'].setValue(this.client.email);
    this.editClientForm.controls['city_id'].setValue(this.selectedCity = this.cityes.filter(
     x => x.city_id === this.client.city
     .map(x => x.city_id)[0])
     .map(y => y.name).join(''))
 }
}

【问题讨论】:

  • 这是因为您在客户端数组中有city_id: '3',,您正在修补到formcontrol
  • 你能尝试一下如何解决这个问题吗?
  • 在自动完成输入任何内容之前,您想默认显示城市名称吗?
  • 是的,我想默认显示城市名称。在这个经验中。佛罗里达
  • 请问可以吗?

标签: angular typescript autocomplete angular-material angular-material2


【解决方案1】:

我已添加 [(ngModel)] = "selectedCity" 以在输入 autocomplete 之前在文本框中设置默认值。我已经在 ts 文件中设置了属性 selectedCity 的值。我还更改了 [formControl]="city_id" 以将其与 ts 文件的 formControl 属性匹配。现在Florida 将默认显示。

以下是完整代码 -

autocomplete-overview-example.html

<form [formGroup]="myform">
    <input formControlName="client_name"  placeholder="name">
    <input formControlName="email"  placeholder="email" >
    <input formControlName="city_id" placeholder="City" [(ngModel)] = "selectedCity" aria-label="State" [matAutocomplete]="auto" Input [formControl]="city_id">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let item of filteredOptionsCity | async" [value]="item.name">
        <span>{{ item.name }}</span> 
      </mat-option>
    </mat-autocomplete> 
  </form>

autocomplete-overview-example.ts

import { Component } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';

import { Observable } from 'rxjs/Observable';
import { startWith } from 'rxjs/operators/startWith';
import { map } from 'rxjs/operators/map';

export class City {
  constructor(public name: string, public city_id: string) { }
}
export class Client {
  constructor(public client_name: string, public city_id: string, public email: string) { }
}
/**
 * @title Autocomplete overview
 */
@Component({
  selector: 'autocomplete-overview-example',
  templateUrl: 'autocomplete-overview-example.html',
  styleUrls: ['autocomplete-overview-example.css']
})
export class AutocompleteOverviewExample {
  stateCtrl: FormControl;
  filteredStates: Observable<any[]>;
 filteredOptionsCity: any;
  city_id: FormControl = new FormControl();
  myform: FormGroup;


  city: City[] = [
    {
      name: 'Arkansas',
      city_id: '1'
    },
    {
      name: 'California',
      city_id: '2'
    },
    {
      name: 'Florida',
      city_id: '3'
    },
    {
      name: 'Texas',
      city_id: '4'
    }
  ];
  client: Client[] = [
    {
      client_name: 'MyName',
      city_id: '3',
      email: 'myemail@gmail.com'
    }
  ];
  selectedCity:string = this.city.filter(x=> x.city_id == this.client.map(x => x.city_id)[0]).map( y => y.name).join("");

  constructor(public fb: FormBuilder) {


    this.myform = this.fb.group({
      'city_id': new FormControl('', Validators.required),
      'client_name': new FormControl('', Validators.required),
      'email': new FormControl('', Validators.required)
    });
  }

ngOnInit(){
   this.populateForm();
   this.filteredOptionsCity = this.city_id.valueChanges.pipe(
      startWith(''),
      map(value => this.filterCity(value))
    );

}
filterCity(val: string): City[] {
    if (val) {
      let filterValue = val.toLowerCase();
      console.log(this.city)
      return this.city.filter(city => city.name.toLowerCase().startsWith(filterValue));
    }

    return this.city;
  }
  populateForm() {

    this.myform.patchValue({
      city_id: this.client.map(x => x.city_id),
      email: this.client.map(x => x.email),
      client_name: this.client.map(x => x.client_name)

    });

    console.log(this.myform.controls);

  }

}

这里是stackblitz的更新链接

https://stackblitz.com/edit/angular-g2hcvs-gpfwjr

【讨论】:

  • 感谢您的回答。在 stackblitz 中效果很好,但在我的实际项目中不起作用。如果可以,请查看我的编辑帖子并建议我,我的项目中有什么问题。非常感谢
  • 您将city_id 设置为this.editClientForm.controls['city_id'].setValue(this.client.city); 中的数组this.client.city,它应该是像this.client.city.map(x =&gt; x.city_id).join(""); 这样的单个值
  • selectedCity:string = this.cityes.filter(x=> x.city_id == this.client.city).map(x => x.city_id).join(''); -->运算符'=='不能应用于类型'string'和'City[]'
  • 你有没有像上面的例子那样使用ngModel?什么是城市?你为什么要过滤它
  • 应该是selectedCity:string = this.cityes.filter(x=&gt; x.city_id == this.client.city.map(x =&gt; x.city_id)[0]).map(x =&gt; x.city.name).join('');
猜你喜欢
  • 2018-07-20
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多