【问题标题】:Angular 4 @ngui-autocompleteAngular 4 @ngui-autocomplete
【发布时间】:2018-02-09 07:34:18
【问题描述】:

我正在尝试在 Angular 4 项目中使用库 @ngui-autocomplete。我使用表单在数据库中创建新条目以及更新/编辑现有条目。 我的自动完成输入的代码如下:

<div [ngClass]="{
              'form-group': true, 'row' : true,
              'has-danger': incidentForm.get('doctor').invalid && ( incidentForm.get('doctor').touched || incidentForm.get('doctor').dirty ),
              'has-success': incidentForm.get('doctor').valid && ( incidentForm.get('doctor').dirty || incidentForm.get('doctor').touched )
           }">
  <label for="doctor" class="col-sm-2 col-form-label">Ιατρός:</label>
  <div class="col-6">

    <input ngui-auto-complete [ngClass]="{
              'form-control': true,
              'form-control-danger': incidentForm.get('doctor').invalid && ( incidentForm.get('doctor').touched || incidentForm.get('doctor').dirty ),
              'form-control-success': incidentForm.get('doctor').valid && ( incidentForm.get('doctor').dirty || incidentForm.get('doctor').touched )
              }"
           name="doctor" formControlName="doctor"
           id="doctor" [source]="doctors"
           autocomplete="off"
           [list-formatter]="'lastName firstName'"
           value-formatter="lastName firstName"
           select-value-of="id"
           required >

    <!-- VALIDATION -->
    <div class="form-control-feedback"
         *ngIf="incidentForm.get('doctor').hasError('required') && incidentForm.get('doctor').touched">
      {{ validationMessages.doctor.required }}
    </div>
    <!-- END OF VALIDATION -->
  </div>
</div>

我的 form.ts 代码是:

import {Component, OnInit} from '@angular/core';
import {IncidentsService} from '../incidents.service';
import {Patient} from '../../patients/patient';
import {Doctor} from '../../doctors/doctor';
import {Clinic} from '../../clinics/clinic';
import {Incident} from '../incident';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {SigningDoctor} from '../../signing-doctors/signing-doctor';
import {HttpErrorResponse} from '@angular/common/http';
import {ActivatedRoute} from '@angular/router';

import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';


@Component({
  selector: 'app-incident-form',
  templateUrl: './incident-form.component.html',
  styleUrls: ['./incident-form.component.css']
})
export class IncidentFormComponent implements OnInit {

  private incident: Incident;
  private id;

  private incidentForm: FormGroup;
  private patients: Patient[] = [];
  private doctors: Doctor[] = [];
  private clinics: Clinic[] = [];
  private signingDoctors: SigningDoctor[] = [];
  private doctor: Doctor;

  private errorMsg;


  constructor(private incidentsService: IncidentsService, private formBuilder: FormBuilder,  private route: ActivatedRoute,  private sanitizer: DomSanitizer) {
    this.createForm();
  }

  createForm() {

    this.incidentForm = this.formBuilder.group({
      protocolNo: ['', [Validators.required, Validators.pattern('^[0-9]{1,}')]],
      date: ['', Validators.required],
      mikro: ['', Validators.required],
      makro: ['', Validators.required],
      yliko: ['', Validators.required],
      anoso: [''],
      histo: [''],
      klinikesPlirofories: [''],
      simpliromatikiEkthesi: [''],
      symperasma: ['', Validators.required],
      patient: ['', Validators.required],
      doctor: ['', Validators.required],
      clinic: [''],
      isPayed: ['', Validators.required],
      signingDoctor: ['', Validators.required]
    });

  }


  ngOnInit() {

    this.parseID();
    this.getIncidentByID();
    this.getRelatedData();
  }

  private parseID() {

    this.route.params
      .catch(error => {
        console.log('error catched', error);

        return Observable.of({description: error});
      })
      .subscribe(
        params => {
          this.id = +params['id'];
        }
      );
  }

  private setFormValues(response){
    this.incidentForm.get('protocolNo').setValue(response.protocolNo);
    this.incidentForm.get('date').setValue(response.date);
    this.incidentForm.get('mikro').setValue(response.mikro);
    this.incidentForm.get('makro').setValue(response.makro);
    this.incidentForm.get('yliko').setValue(response.yliko);
    this.incidentForm.get('anoso').setValue(response.anoso);
    this.incidentForm.get('histo').setValue(response.histo);
    this.incidentForm.get('klinikesPlirofories').setValue(response.klinikesPlirofories);
    this.incidentForm.get('simpliromatikiEkthesi').setValue(response.simpliromatikiEkthesi);
    this.incidentForm.get('symperasma').setValue(response.symperasma);
    this.incidentForm.get('isPayed').setValue(response.isPayed);
    this.incidentForm.get('doctor').setValue(response.doctor);
  }

  autocompleListFormatter = (data: any) => {
    let html = `${data.lastName} ${data.firstName}`;
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }


  private getIncidentByID() {

    this.incidentsService.getIncidentByID(this.id)
      .subscribe(
        response => {
          this.incident = response;
          this.setFormValues(response);

        },
        (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
            // A client-side or network error occurred. Handle it accordingly.
            console.log('An error occurred:', err.error.message);
          } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
          }
        });
  }

  getRelatedData() {

    this.incidentsService.getRelatedData().subscribe(
      results => {
        this.patients = results[0];
        this.doctors = results[1];
        this.clinics = results[2];
        this.signingDoctors = results[3];
      },
      (err: HttpErrorResponse) => IncidentFormComponent.handleError
    );
  }

  submitForm() {

    this.incidentsService.submitForm(this.incidentForm.value).subscribe(
      res => {
        // this.incident = res;
        console.log('Submit Form Response: ' + JSON.stringify(res));

        this.incidentForm.reset();
        // this.createForm();
      },
      (err: HttpErrorResponse) => IncidentFormComponent.handleError
    );

  }

  static handleError(err) {

    if (err.error instanceof Error) {
      // A client-side or network error occurred. Handle it accordingly.
      console.log('An error occurred:', err.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
    }

  }

  validationMessages = {
    protocolNo: {
      required: 'Ο Αριθμός Πρωτοκόλλου είναι υποχρεωτικός.',
      pattern: 'Ο Αριθμός Πρωτοκόλλου Έχει Λάθος Μορφή.'
    },
    date: {
      required: 'Η Ημερομηνία Είναι Υποχρεωτική. ',
      pattern: 'Λάθος Μορφή Ημερομηνίας.'
    },
    symperasma: {
      required: 'Το Συμπερασμα είναι Υποχρεωτικό.',
    },
    patient: {
      required: 'Η Επιλογή Ασθενή Είναι Υποχρεωτική.'
    },
    doctor: {
      required: 'Η Επιλογή Ιατρού Είναι Υποχρεωτική.'
    },
    signingDoctor: {
      required: 'Η Επιλογή Υπογράφων Ιατρού Είναι Υποχρεωτική.'
    },
    yliko: {
      required: 'Το πεδίο υλικό είναι υποχρεωτικό.'
    },
    mikro: {
      required: 'Το πεδίο μίκροσκοπικά είναι υποχρεωτικό.'
    },
    makro: {
      required: 'Το πεδίο μακροσκοπικά είναι υποχρεωτικό.'
    },
    isPayed: {
      required: 'Το πεδίο πληρωμή είναι υποχρεωτικό.'
    },

    success: 'Yeah'
  };

}

对于创建条目,一切都按预期工作。 但是,当我更新现有条目时,可以使用命令将值设置为自动完成输入组件

this.incidentForm.get('doctor').setValue(response.doctor);

虽然 form.value 在我得到的输入字段内是正确的: [object Object] 而不是命令中声明的“lastName firstName”

value-formatter="lastName firstName"

我想我错过了一些非常简单的东西,但我无法得到它。

【问题讨论】:

  • 您能否将 getIncidentByID 的代码粘贴到*服务中以及来自该服务的 json 响应?
  • 对象接收正确。我可以在 form.value 中看到它。问题在于输入自动完成字段,而不是显示“lastName firstName”,而是显示 [object Object]
  • 我明白了,这就是为什么我要求你粘贴 JSON 响应和服务代码

标签: angular autocomplete ngui


【解决方案1】:

解决方案很简单。刚刚添加

 display-property-name="lastName firstName"

<input ngui-auto-complete name="doctor" 
   formControlName="doctor" 
   id="doctor" 
   [source]="doctors" 
   autocomplete="off" 
   [list-formatter]="'lastName firstName'" 
   value-formatter="lastName firstName" 
   display-property-name="lastName firstName"
   [(ngModel)] = "Doctor" 
   required>

【讨论】:

  • 如果我有那个下拉菜单,我如何通过传递 int 而不是对象 @mixtou 来获取该数据的 id 或主键
【解决方案2】:

您需要在输入中传递[(ngModel)]

因为它是自动完成的并且作为下拉菜单工作,所以您需要绑定您的模型,这样您就可以搜索数据并使用两种方式数据绑定选择该数据。

<input ngui-auto-complete name="doctor" 
       formControlName="doctor" 
       id="doctor" 
       [source]="doctors" 
       autocomplete="off" 
       [list-formatter]="'lastName firstName'" 
       value-formatter="lastName firstName" 
       [(ngModel)] = "Doctor" 
       required>

【讨论】:

  • 这应该如何完成?
  • 因为它是自动完成的并且作为下拉菜单工作,所以您需要绑定模型,这样您就可以搜索数据并使用两种数据绑定方式选择该数据。
  • 你能说明输入应该如何形成吗?我问这些问题是为了提高你答案的质量,所以我可以投票。作为 SO 答案的一般规则;更多信息更好。我认为投反对票的人(不是我)觉得你的回答有点简约。
  • 在上面的示例中,您可以在 ngui-autocomplete 中看到您需要 [source],它返回数据,模型决定数据的返回类型,您希望数据采用哪种格式。
  • 这里 Doctor 是模型。
猜你喜欢
  • 2017-12-28
  • 2021-10-12
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2014-01-30
  • 2016-09-10
相关资源
最近更新 更多