I have a form in which I have to select one or multiple customers, a date picker and a button. The customer select has a "+" sign on the right that displays a new customer select right below with another "+" so you can add as many as needed.
Html:
<div fxLayout="row span" fxFlex.gt-sm="50" class="pr-20">
<ng-container *ngFor="let item of [].constructor(customerNumber); let i = index let isLast = last">
<mat-form-field appearance="outline" fxFlex="80">
<mat-label>Customer</mat-label>
<autocomplete-input-field formControlName="{{ 'customer' + i }}" required
[options]="customers"
[getOptionIdFunction]="getCustomerId" [getOptionLabelFunction]="getCustomerName"
>
</autocomplete-input-field>
<mat-icon matSuffix class="secondary-text">account_circle</mat-icon>
</mat-form-field>
<button *ngIf="isLast" mat-icon-button style="margin-top: 10px" color="primary" (click)="addCustomer()">
<mat-icon>add</mat-icon>
</button>
</ng-container>
</div>
Typescript
export class CustomerHistoryMetricsComponent implements OnInit, OnDestroy {
@ViewChild('downloadLink', {static: true}) private downloadLink: ElementRef;
private _unsubscribeAll: Subject<any>;
downloadingExcel: boolean;
date = new FormControl(moment());
yearSelected: number;
monthSelected: number;
customers: Customer[];
customerNumber = 1;
form: FormGroup;
constructor(
private _fuseTranslationLoaderService: FuseTranslationLoaderService,
private customerService: CustomerService,
private formBuilder: FormBuilder,
private metricsService: MetricsService,
private fileService: FileService,
) {
this._fuseTranslationLoaderService.loadTranslations(english, catalan, spanish);
}
ngOnInit(): void {
this._unsubscribeAll = new Subject();
this.downloadingExcel = false;
this.form = this.formBuilder.group({
customer1: ['', Validators.required],
startDate: ['', Validators.required],
});
this.customerService.getAllActiveAndAllowedByPermission(Permission.CONSULT_CUSTOMERS)
.pipe(takeUntil(this._unsubscribeAll))
.subscribe(customers => {
this.customers = customers;
// this.setCustomerIfItIsTheOnlyOne();
});
}
ngOnDestroy(): void {
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
public getCustomerId(customer: Customer): number {
return customer.id;
}
public getCustomerName(customer: Customer): string {
return customer.name;
}
public addCustomer(): void {
this.customerNumber = this.customerNumber + 1;
const controlName = `customer${this.customerNumber}`;
this.form.addControl(controlName, new FormControl(''));
}
I am using angular FormBuilder but I don't know how can I retrieve the values that the selects (autocomplete-input field) have when they are generated by an ngFor loop, I've tried like 15 different solutions but at this point I think I shouldnt be using ngFor