What you want to do may be a bit far-fetched. I have a date/time range that triggers a query to the database. This data is the content with which I need to fill this selector, and I need the selector to be filled with the first element selected.
So far what I have achieved is that the selector loads the content of what the database brings but I don't know how to make that content show the first one.
HTML:
<form [formGroup]="formGateway">
<mat-form-field class="textBox" appearance="fill">
<mat-label> Gateway seleccionado </mat-label>
<mat-select
formControlName="gatewayId"
>
<mat-option
*ngFor="let gw of basicGatewayDTO"
[value]="gw.gateway_id"
>
{{ gw.gateway_name }}
</mat-option>
</mat-select>
</mat-form-field>
</form>
TypeScript:
formGateway: any;
basicGatewayDTO: basicGatewayDTO[] = [];
constructor(
private formBuilder: FormBuilder,
) {
this.formGateway = formBuilder.group({ gatewayId: new FormControl('') });
}
ngOnInit(): void {
this.FiltrarGateways().then((respuesta) => {
let respStr = JSON.stringify(respuesta);
this.basicGatewayDTO = JSON.parse(respStr);
});
}
I summarized the code so that it is understood how I am handling it (for example, the method that returns the promise that brings the information is not shown), however I am open to other ways of doing it.
What I want to do is set the selector property to have the first index or first option selected, assuming that what the database brings exists. It could be something like this:
setValueSelector(valor: string){
this.formGateway.gatewayId.setValue(valor);
}
Or instead of setting the value, set the position, the option, whatever is best and most practical to solve it.
I appreciate any information on this
You would have to enter
formControlName
and set the first value that the JSON brings you: