FormArray with HostListener in Directive


FormArray with HostListener in Directive



I'm creating my inputs form within loop:


<tr formArrayName="items" *ngFor="let vatCat of items.controls; let i = index">
<td [formGroupName]="i">
<input name="symbol" minlength="1" maxlength="1" [(ngModel)]="symbol" appUppercase type="text" formControlName="symbol">
</td>
<td [formGroupName]="i">
<input name="value" type="number" [ngModel]="0" formControlName="value">
</td>
<td [formGroupName]="i">
<span class="table-remove">
<button (click)="removeItem(i)" type="submit" class="btn btn-danger btn-rounded btn-sm my-0">Usuń</button>
</span>
</td>
....



Then I had to change every value in symbol input ot uppercase so I created an directive:


@Directive({
selector: '[ngModel][appUppercase]'
})
export class UppercaseDirective {
@Output() ngModelChange: EventEmitter<any> = new EventEmitter();
value: any;

@HostListener('input', ['$event']) onInputChange($event) {
this.value = $event.target.value.toUpperCase();
this.ngModelChange.emit(this.value);
}
}



It works great until I add a new form, this is how my model looks like:


formArray = this.formBuilder.group({
items: this.formBuilder.array()
});

buildItem(): FormGroup {
return this.formBuilder.group({
symbol: new FormControl('', this.vatCategoryValidation.bind(this)),
value: new FormControl('', this.vatValueValidation.bind(this))
});
}
addItem() {
this.items.push(this.buildItem());
}



There are currently two issues, the first one is that @Output value propagate to every each input instead of this one related to it. Second is an error xpression has changed after it was checked. Previous value: 'ng-valid: false'. Current value: 'ng-valid: true'.


xpression has changed after it was checked. Previous value: 'ng-valid: false'. Current value: 'ng-valid: true'.



enter image description here
Is it possible to make it works together?




1 Answer
1



Okay I make it work, solved two problems at once by changing a little my Directive:


@Directive({
selector: '[appUppercase]'
})
export class UppercaseDirective {
@Output() ngModelChange: EventEmitter<any> = new EventEmitter();
value: any;

constructor(private el: ElementRef) {}

@HostListener('input') onInputChange() {
this.el.nativeElement.value = this.el.nativeElement.value.toUpperCase();
}
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Render GeoTiff to on browser with leaflet

How to get chrome logged in user's email id through website

using states in a react-navigation without redux