J'ai le composant , où j'utilise primeNG p-autocomplete

Voici le html de ce composant

 <form #addressForm="ngForm" novalidate name="AddressForm">
<div class="form-group">
    <label for="Line1">{{ 'AddressLine1' | localize }} *</label>
    <p-autoComplete
        #addressLine1="ngModel"
        [(ngModel)]="selectedAddresses"
        [suggestions]="addresses"
        field="line1"
        [inputStyle]="{ width: '100%' }"
        name="line1"
        (completeMethod)="searchAddress($event)"
        [size]="10"
        placeholder="{{ 'Line1Placeholder' | localize }}"
        (onSelect)="onSelectAddress($event)"
        [minLength]="3"
        required
        (change)="checkValidity()"
    ></p-autoComplete>
    <validation-messages [formCtrl]="addressLine1"></validation-messages>
  {{address.line1}}
</div>

<div class="form-group">
    <label for="Line2">{{ 'AddressLine2' | localize }}</label>
    <input
        id="Line2"
        class="form-control"
        #line2Input="ngModel"
        type="text"
        name="Line2"
        placeholder="{{ 'Line2Placeholder' | localize }}"
        [(ngModel)]="address.line2"
        maxlength="128"
        (change)="checkValidity()"
    />
</div>
<div class="form-group">
    <label for="Line3">{{ 'AddressLine3' | localize }} </label>
    <input
        id="Line3"
        class="form-control"
        #line3Input="ngModel"
        type="text"
        name="Line3"
        [(ngModel)]="address.line3"
        maxlength="128"
        (change)="checkValidity()"
    />
    <validation-messages [formCtrl]="line3Input"></validation-messages>
</div>

Et voici une partie tapuscrite du composant

  import { Component, Injector, forwardRef, ViewChild, AfterContentChecked, ElementRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, ValidationErrors } from '@angular/forms';
import { AddressType } from '@shared/AppEnums';
import { AppComponentBase } from '@shared/common/app-component-base';
import { AddressDto } from '@shared/service-proxies/service-proxies';
import { SelectItem } from 'primeng/primeng';
import PlaceResult = google.maps.places.PlaceResult;
import { Feature } from '../../dto/mapboxOutput';
import { MapboxServiceService } from '../mapbox-service';

@Component({
    selector: 'edit-main-address',
    templateUrl: './edit-main-address.component.html',
    providers: [
        { provide: NG_VALUE_ACCESSOR, useExisting: EditMainAddressComponent, multi: true },
        {
            provide: NG_VALIDATORS,
            useExisting: forwardRef(() => EditMainAddressComponent),
            multi: true,
        },
    ],
})
export class EditMainAddressComponent extends AppComponentBase implements ControlValueAccessor, AfterContentChecked {
    @ViewChild('addressForm') addressForm;
    @ViewChild('search') public searchElement: ElementRef;
    @ViewChild('postCode') public postCodeElement: ElementRef;
    @ViewChild('town') public townElement: ElementRef;
    @ViewChild('country') public countryElement: ElementRef;
    required: string | boolean;

    private changed = [];
    private touched = [];


    disabled: boolean;
    address: AddressDto = new AddressDto();
    addressTypes: SelectItem[] = [];
    addresses: any[] = [];
    selectedAddresses: string;
    public lat: any;
    public lng: any;
    public postCode: string;
    public country: string;
    public city: string;
    public line1: any;

    constructor(injector: Injector, private mapboxService: MapboxServiceService) {
        super(injector);
        this.addressTypes.push({ label: this.l('Address.Main'), value: AddressType.Main });
        this.addressTypes.push({ label: this.l('Address.Billing'), value: AddressType.Billing });
        this.addressTypes.push({ label: this.l('Address.Delivery'), value: AddressType.Delivery });
        this.addressTypes.push({ label: this.l('Address.Correspondence'), value: AddressType.Correspondence });
    }

    ngAfterContentChecked(): void {
        this.checkValidity();
    }

    checkValidity(): void {}

    get adressResult(): AddressDto {
        return this.address;
    }

    set addressResult(value: AddressDto) {
        if (this.address !== value) {
            this.address = value;
            this.selectedAddresses = value.line1;
            this.changed.forEach(f => f(value));
        }
    }

    registerOnChange(fn: any): void {
        this.changed.push(fn);
    }

    registerOnTouched(fn: any): void {
        this.touched.push(fn);
    }

    setDisabledState(isDisabled: boolean): void {
        this.disabled = isDisabled;
    }

    writeValue(obj: AddressDto): void {
        if (obj) {
            this.addressResult = obj;
            this.selectedAddresses = this.address.line1;
            this.checkValidity();
        }
    }

    validate(): ValidationErrors {
        if (!this.addressForm.valid) {
            return { message: 'custom error' };
        }
        return null;
    }

    registerOnValidatorChange(fn: () => void): void {
        this.checkValidity = fn;
    }

    searchAddress(event: any): any {
        const searchTerm = event.query.toLowerCase();
        if (searchTerm && searchTerm.length > 0) {
            this.mapboxService.addressSearch(searchTerm).subscribe((features: Feature[]) => {
                this.addresses = [...features.map(e => ({ name: e.place_name, id: e.place_name, feature: e }))];
            });
        } else {
            this.addresses = [];
        }
    }

    onSelectAddress(event: any): any {
        if (event.feature.id.startsWith('address')) {
            this.address.line1 = event.name;
            this.address.longitude = event.feature.center[0];
            this.address.latitude = event.feature.center[1];
            this.address.postTown = event.feature.context.filter(element => element.id.startsWith('place'))[0].text;
            this.address.county = event.feature.context.filter(element => element.id.startsWith('district'))[0].text;
            this.address.country = event.feature.context.filter(element => element.id.startsWith('country'))[0].text;
            this.address.postCode = event.feature.context.filter(element => element.id.startsWith('postcode'))[0].text;
        }
        if (event.feature.id.startsWith('postcode')) {
            this.address.line1 = event.name;
            this.address.longitude = event.feature.center[0];
            this.address.latitude = event.feature.center[1];
            this.address.postTown = event.feature.context.filter(element => element.id.startsWith('place'))[0].text;
            this.address.county = event.feature.context.filter(element => element.id.startsWith('district'))[0].text;
            this.address.country = event.feature.context.filter(element => element.id.startsWith('country'))[0].text;
            this.address.postCode = event.feature.text;
        }
    }
    ngOnInit(): void {}
}

Mon problème est que tous les champs avec ngModel sont bien définis, mais p-autocomplete n'est pas défini

J'ai essayé de définir la valeur sur selectedAddresses comme ceci this.selectedAddresses = value.line1; qui est une chaîne et si je fais console.log(this.selectedAddresses) je le vois dans la console. Mais il n'est pas défini sur le champ p-autocomplete, je ne vois pas de valeur dans l'entrée

0
Eugene Sukh 24 févr. 2020 à 12:41

1 réponse

Meilleure réponse

Changez le type de selectedAddresses en any à partir de string puis la directive field de p-autocomplete fera le reste :

selectedAddresses: any;

Maintenant field="line1" affichera selectedAddresses.line1 dans votre champ de saisie

<p-autoComplete
        #addressLine1="ngModel"
        [(ngModel)]="selectedAddresses"
        [suggestions]="addresses"
        field="line1"
        [inputStyle]="{ width: '100%' }"
        name="line1"
        (completeMethod)="searchAddress($event)"
        [size]="10"
        placeholder="{{ 'Line1Placeholder' | localize }}"
        (onSelect)="onSelectAddress($event)"
        [minLength]="3"
        required
        (change)="checkValidity()"
    ></p-autoComplete>
1
Mustahsan 24 févr. 2020 à 10:18