0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.