在打字稿中填充自动填充材料

时间:2018-04-11 07:37:55

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

我有这个例子Demo

我试图在城市中显示佛罗里达,但对我来说不起作用,我只能显示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 no。

我的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>

我的结果:

enter image description here

我想表明:

**`

  

client_name:MyName city_id:Florida电子邮件: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

    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(''))
 }
}

1 个答案:

答案 0 :(得分:0)

在输入自动填充功能之前,我已添加[(ngModel)] = "selectedCity"以设置文本框中的默认值。我在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>

<强>自动完成-概述-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