Tengo un formulario muy sencillo con un Autocomplete de Angular Material que hace su trabajo, pero recibo el error "Error: formControlName must be used with a parent formGroup directive." Decir que aun estoy muy verde con Angular.
TS:
export class SquareFootDialogComponent implements OnInit {
plantFormControl = new FormControl();
options: PlantInterface[] = this.data.plants;
filteredPlants!: Observable<PlantInterface[]>;
constructor(
private dialogRef: MatDialogRef<SquareFootDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: {sf: SquarefootInterface, plant: PlantInterface, plants: PlantInterface[]}
) { }
ngOnInit(): void {
this.filteredPlants = this.plantFormControl.valueChanges.pipe(
startWith(''),
map(value => (typeof value === 'string' ? value : value.name)),
map(name => (name ? this.filterPlants(name) : this.options.slice())),
);
}
// Show plant name in new plant form when filtering
displayFn(plant: PlantInterface): string {
return plant && plant.name ? plant.name : '';
}
// Filter results when type a name
private filterPlants(value: string): PlantInterface[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.name.includes(filterValue));
}
save(){
this.dialogRef.close(this.plantFormControl.value);
}
close(){
this.dialogRef.close();
}
HTML:
<form *ngIf="!data.sf.plant" (ngSubmit)="save()">
<mat-form-field appearance="fill">
<mat-label>Añadir cultivo</mat-label>
<input type="text"
formControlName="plantName"
placeholder="Selecciona un cultivo"
matInput
[formControl]="plantFormControl"
[matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let plant of filteredPlants | async" [value]="plant.name">
<img [src]="'assets/plants/thumbs/' + plant.img" width="30" class="mat-autocomplete--img">
{{plant.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<div class="row between-xs">
<button mat-raised-button type="submit">
Crear
</button>
<button mat-raised-button type="button" (click)="close()">
Cancelar
</button>
</div>
</form>
He tratado de establecer un FormGroup con los form controls, pero cuando lo hago, deja de funcionar el autocomplete:
INTENTO ARREGLARLO CON:
form!: FormGroup;
ngOnInit(): void {
// New Bed Form onInit
this.form = this.fb.group({
plantName: ['', Validators.required],
});
Pero al hacerlo, deja de funcionar el autocomplete.
Gracias de antemano.