Javascript Can';p-autocomplete中ngModel的t绑定值
我有一个组件,其中我使用了primingJavascript Can';p-autocomplete中ngModel的t绑定值,javascript,angular,typescript,primeng,Javascript,Angular,Typescript,Primeng,我有一个组件,其中我使用了primingp-autocomplete 下面是这个组件的html <form #addressForm="ngForm" novalidate name="AddressForm"> <div class="form-group"> <label for="Line1">{{ 'AddressLine1' | localize }} *</label> <p-autoComplete
p-autocomplete
下面是这个组件的html
<form #addressForm="ngForm" novalidate name="AddressForm">
<div class="form-group">
<label for="Line1">{{ 'AddressLine1' | localize }} *</label>
<p-autoComplete
#addressLine1="ngModel"
[(ngModel)]="address.line1"
[suggestions]="addresses"
field="name"
[inputStyle]="{ width: '100%' }"
name="lin1"
(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>
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 = [];
public selectedAddress: PlaceResult;
disabled: boolean;
address: AddressDto = new AddressDto();
addressTypes: SelectItem[] = [];
addresses: any[] = [];
selectedAddresses: any = null;
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 value(): AddressDto {
return this.address;
}
set value(value: AddressDto) {
if (this.address !== value) {
this.address = value;
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.address = obj;
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 {}
}
我的问题是ngModel设置的所有字段都很好,但没有设置p-autocomplete
但是如果我在input下写{{{address.line1}}
,一切正常。你可以从截图上看到。
哪里有我的问题,我如何解决它?您可以使用searchAddress()搜索地址,它填充addresses属性。 地址是复杂的对象而不是简单的字符串,对吗
[suggestions]="addresses"
(completeMethod)="searchAddress($event)"
[(ngModel)]="address.line1"
因此,p-autocomplete的ngModel将是所选的地址对象。
然后将ngModel绑定到address.line1,该地址应为字符串。
此外,address.line1随后由onSelectAddress方法填充:
this.address.line1 = event.name;
我建议您将所选地址对象与address.line1分开,并将ngModel绑定到另一个属性-例如[(ngModel)]=“selectedAddress”您可以使用searchAddress()搜索地址,它将填充addresses属性。 地址是复杂的对象而不是简单的字符串,对吗
[suggestions]="addresses"
(completeMethod)="searchAddress($event)"
[(ngModel)]="address.line1"
因此,p-autocomplete的ngModel将是所选的地址对象。
然后将ngModel绑定到address.line1,该地址应为字符串。
此外,address.line1随后由onSelectAddress方法填充:
this.address.line1 = event.name;
我建议您将所选地址对象与address.line1分开,并将ngModel绑定到不同的属性-例如[(ngModel)]=“selectedAddress”如果在@PeterFromCologne的解决方案之后仍然不起作用,请确保[multiple]设置为false
<p-autoComplete
[style]="{ width: '100%' }"
[(ngModel)]="selectedLabTemplate.testName"
[suggestions]="selectedLabTemplate"
(completeMethod)="GetLabTest($event)"
[multiple]="false"
></p-autoComplete>
如果在@peterfromcolone的解决方案之后仍然不起作用,请确保将[multiple]设置为false
<p-autoComplete
[style]="{ width: '100%' }"
[(ngModel)]="selectedLabTemplate.testName"
[suggestions]="selectedLabTemplate"
(completeMethod)="GetLabTest($event)"
[multiple]="false"
></p-autoComplete>
set这里的问题是,当我打开modal(HTML是modal的一部分)时,我尝试在set
中将值设置为p-autocomplete
,就像这样设置值(值:AddressDto){if(this.address!==value){this.address=value;this.selectedAddress=value.line1;this.changed.forEach(f=>f(value));}}
这不起作用。但对于其他人来说,如果我改为[(ngModel)]=“selectedAddress”,效果会很好
就像你告诉我的那样我希望我的答案能给你正确的方向,你需要进行更多的调查。在上面的代码中,this.selectedaddress=value.line1是错误的。如果答案对你有帮助,请投赞成票或接受。这里的问题是当我打开modal(HTML是modal的一部分)时我尝试在set
中将值设置为p-autocomplete
如下set value(value:AddressDto){if(this.address!==value){this.address=value;this.selectedaddress=value.line1;this.changed.forEach(f=>f(value));}
这不起作用。但对于其他人来说,如果我改为[(ngModel)]=“selectedAddress”,效果会很好
如您所说,我希望我的答案能为您提供正确的方向,您需要进行更多的调查。在上面的代码中,this.selectedaddress=value.line1是错误的。如果答案对您有帮助,请投赞成票或接受。谢谢您的回答,您能更好地阐述它吗?并解释更改的原因以及更改的内容和方式这会改变结果吗?对我来说,如果你在ts文件中赋值,它没有绑定到p-autocomplete,当倍数设置为true时,它发生了,这意味着p-autocomplete需要多个值,因此无法绑定单个值谢谢你的回答,你能更好地表达它吗?例如明确更改的原因以及更改的内容和方式?对于我来说,如果在ts文件中指定一个值,它不会绑定到p-autocomplete,并且当倍数设置为true时,它会发生,这意味着p-autocomplete需要多个值,因此无法绑定单个值