Patchform автозаполнение материала с помощью Angular 6 - PullRequest
0 голосов
/ 18 октября 2018

У меня есть этот пример DEMO В этой демонстрации у меня проблема с автозаполнением, поэтому я хочу исправить название города и отправить идентификатор города.Когда я добавляю пункт работает хорошо.

Пожалуйста, вы можете увидеть мой код, как показано ниже:

У меня есть этот машинописный код:

export class City {
  constructor(public name: string, public city_id: string) { }
}
export class Client {
  constructor(public client_name: string, public city_id: City[], public email: string) { }
}
 ....
  city: City[] = [
    {
      name: 'PkMGo',
      city_id: '1'
    },
    {
      name: 'Y4FQS',
      city_id: '2'
    },
    {
      name: 'Mlld0',
      city_id: '3'
    },
    {
      name: 'q0KTN',
      city_id: '4'
    }
  ]

  client: Client[] = [
    {
      client_name: 'My Name',
      city_id: ['3', '4'],
      email: 'myemail@gmail.com'
    }
  ];


  constructor(public fb: FormBuilder) {
    this.myform = this.fb.group({
      'city_id': this.fb.array([], Validators.required),
      'client_name': new FormControl('', Validators.required),
      'email': new FormControl('', Validators.required)
    });
      this.filteredOptionsCity = this.myform.controls['city_id'].valueChanges
      .pipe(
        startWith(['']),
      );
  }

  ngOnInit() {
    this.populateForm();
  }
  get formData() {
    return <FormArray>this.myform.get('city_id');
  }
  populateForm() {

    this.myform.patchValue({
      email: this.client.map(x => x.email),
      client_name: this.client.map(x => x.client_name),
      city_id: this.client.forEach(x => {
        this.formData.push(new FormControl(x.city_id))
      })
        });  
  }
  onAddprod() {
    let newHbp = this.myform.value
  }
  onAddItem() {
    (<FormArray>this.myform.controls['city_id']).push(new FormControl('', Validators.required));
  }
  get productIdFormArray() {
    return (<FormArray>this.myform.get('city_id')).controls;
  }
  updateFormProducts(ev: any, idd: any, componentid: any, index) {
    if (ev.isUserInput) {
      if (componentid === 'city_id') {
        console.log(ev.source.viewValue);
        (<FormArray>this.myform.get('city_id')).at(index).patchValue(ev.source.viewValue);
      } else {
        console.log('error');
      }
    }
  }
}

И этот HTML-код:

<form [formGroup]="myform" (ngSubmit)="onAddprod()">
    <input formControlName="client_name"  placeholder="name">
    <input formControlName="email"  placeholder="email" >
        <div formArrayName="city_id">
      <div *ngFor="let s of productIdFormArray; let i = index">
        <mat-form-field class="example-full-width">
          <input [formControlName]="i" matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" >
          <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayWith">
            <mat-option *ngFor="let item of filteredOptionsCity  | async | myPipe: city : 'name': i" (onSelectionChange)="updateFormProducts($event, item.name, 'city_id', i)" [value]="item.city_id">
              <span>{{item.name}}</span>
            </mat-option>
          </mat-autocomplete>
        </mat-form-field>
      </div>
      <div class="input-field col s2">
        <button type="button" class="btn" (click)="onAddItem()">Add Item</button>
      </div>
    </div>
      <button type="submit" class="btn waves-effect waves-light">Register</button>
  </form> 

Проблема в том, что в autocomplete show id города 3 и 4, как на рисунке 1.

image1

Я хочу показать название города,и введите идентификатор города, как на рисунке 2.

image2

Можете ли вы спросить меня, как решить эту проблему?

...