0
votes

I am making use of the mat-autocomplete component with an input as per the examples in the docs, and I have configured the input with a placeholder and a formControlName like so:

<mat-form-field class="example-full-width">
    <input type="text" placeholder="Persona*" aria-label="Number" matInput formControlName="idPersona"
    [matAutocomplete]="autoPersonas">

    <mat-autocomplete autoActiveFirstOption #autoPersonas="matAutocomplete"
        [displayWith]="displayPersona(filteredOptionsPersonas | async)" (optionSelected)="selectedValue($event)">
        <mat-option *ngFor="let option of filteredOptionsPersonas" [value]="option.idPersona">
            <p>{{option.nombre}}</p>
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

I'm also using optionSelected which emits MatAutocompleteSelectedEvent from mat-autocomplete to keep the viewvalue (option selected), the value, the formControlName and the placeholder. The problem is that I can't reach the last two (formControlName and placeholder) from the event object MatAutocompleteSelectedEvent. Is there a way to reach those properties?

1

1 Answers

1
votes

You can pass them to the handler for the optionSelected.

So the method signature can change to selectedValue(autoCompleteEvent: MatAutocompleteSelectedEvent, placeholder: string, controlName: string )

And in your template: (optionSelected)="selectedValue($event, 'Persona*', 'idPersona')" .

Taking a guess here, but if your use case is to clean the control, then you can do it in the controller with subscribing to the controls changes and make an observable like this:

this.formGroup.get('idPersona').valueChanges.subscribe(() => {
  this.formGroup.get('idPersona').setValue(null, {emitEvent: false});
});

Setting the value to an empty string or null/undefined will make the placeholder reappear.