Reputation: 598
I am still learning basic of angular 6 and typescripts and I am not sure how to make this work. I have one field, if user put some number value there (for example "100"), values in other inputs should change. I am pretty sure that I should use debounceTime and 'rxjs' like in this tutorial: https://angular.io/tutorial/toh-pt6, but I can't figure it out how to make this work.
If user put '100' in "how much" field, Tomek's and Magda's field values should change to '50' (100 / 2)
expense-shared.component.html
<div class="form-group">
<label for="name">How much?</label>
<input type="text" class="form-control" id="amount" required
[(ngModel)]="expense.amount" (keyup)="changeListValues(expense.amount)"
name="amount" #amount="ngModel" placeholder="Amount in EUR">
<div [hidden]="amount.valid || amount.pristine" class="alert alert-danger">
Amount is required
</div>
</div>
expense-shared.component.ts
@Input() amountList: Equally[];
changeListValues(expenseTotalAmount: number) {
const checkedAmount = this.amountList.filter(x => x.checked).length;
this.amountList.filter(x => x.checked).forEach(element => {
element.quantity = this.expense.amount / checkedAmount;
});
}
Upvotes: 3
Views: 7549
Reputation: 9201
Additional Information - Using Observables to handle input changes
If anyone comes here and wants to handle input
changes using Observable
, this is how you do.
Assume we have following form (html),
<form [formGroup]="heroForm">
<label>
Name 1:
<input type="text" formControlName="name1" required>
</label>
</form>
If you need to handle input changes for name1
using Observable
, this is how you do in your component.ts
file.
ngOnInit() {
this.logNameChange();
}
logNameChange() {
const nameControl = this.heroForm.get('name1');
nameControl.valueChanges.forEach(
(value: string) => console.log(value)
);
}
The above will log the typed value in the console.
StackBlitz example :- https://stackblitz.com/edit/angular7-input-change-observable?file=src/app/app.component.ts
Link to Angular Document :- https://angular.io/guide/observables-in-angular#reactive-forms
Hope this will help someone.
Cheers!
Upvotes: 2