Eugene Sukh
Eugene Sukh

Reputation: 2737

Can't bind value to ngModel in p-autocomplete in setter

I have component , where I use primeNG p-autocomplete

Here is html of this component

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

and here is typescript part of the component

  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 {}
}

My problem is all fields with ngModel set great, but p-autocomplete is not setted

I tried to set the value to selectedAddresses like this this.selectedAddresses = value.line1; which is string and if I make console.log(this.selectedAddresses) I see it in console. But it not set to the p-autocomplete field, I don't see value in the input

Upvotes: 0

Views: 932

Answers (1)

Mustahsan
Mustahsan

Reputation: 3862

change the type of selectedAddresses to any from string then the field directive of p-autocomplete will do the rest:

selectedAddresses: any;

now field="line1" will show selectedAddresses.line1 in your input field

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

Upvotes: 1

Related Questions