Reputation: 937
I have an input with typeahead using ngx-bootstrap.
<input type="text" class="form-control with-icon" placeholder="Address ..."
formControlName="address" [typeahead]="addressDataSource" typeaheadOptionField="fullAddress" />
My addressDataSource look like this :
[
{
id: '1',
fullAddress: '44000 - Nantes'
},
{
id: '2',
fullAddress: '77400 - Paris'
}
....
]
The problem is when I select a value, I want to show in the input the selected value in fullAddress which work great, but the value of the input should be only the postal code which is 44000 or 77400 here in the example.
I tried to make a Directive like this :
constructor(private model: NgControl) { }
@HostListener('input') inputChange() {
const newValue = this.model.value.split(' ')[0];
this.model.control.setValue(newValue);
this.model.valueAccessor.writeValue(this.model.value);
}
The value change but also the value showed in input change as well.
Upvotes: 0
Views: 211
Reputation: 937
Okay I managed to make it work, in case it would help someone, here is the directive code :
constructor(private model: NgControl) { }
@HostListener('input') inputChange() {
const newValue = this.model.value.split(' ')[0];
this.model.control.setValue(newValue, {
emitEvent: false,
emitModelToViewChange: false
});
}
I didn't get why it didn't work with the code before thought, if someone has the answer I'll update my answer.
Upvotes: 1