I have a need to update the component if the component has an input value. While doing so, I am setting values that would normally be set by inserting text into the input and selecting list value from an autocomplete. Even though I set an object to a FormControl variable, the valueChangespipe doesn't see it that way. But I'm sure the formControl gets the value because on the front-end I show the data by formControl.value ? formControl.value.Name : '' and on my case there's a legitimate name in the form control's input.
This is how I show the data;
<div class="col-6" *ngIf="departmentUserList.length > 0">
<mat-form-field class="full-width">
<input type="text" placeholder="User" matInput [formControl]="departmentUserControl"
[matAutocomplete]="userAutoComplete"
[value]="departmentUserControl.value ? departmentUserControl.value.Name : ''">
<mat-autocomplete #userAutoComplete="matAutocomplete"
(optionSelected)="valueChange('SolvingUser', $event)">
<mat-option *ngFor="let user of filteredUserList | async" [value]="user">
{{user.Name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
This is my valueChanges pipe which I put into the ngOninit;
this.filteredUserList = this.departmentUserControl.valueChanges.pipe(
startWith(''),
map(value => {
console.log("ToFilterValue =>>", value); // this is always '', from the startWith and does not change until I choose from the matAutoComplete
return typeof value === 'string' ? this.filterUser(value) : this.filterUser(value ? value.Name : '')
})
);
This is how I update the value if there's one; (this function is called inside ngOnInit before the declarations of the valueChanges pipes)
mapObjects(){
// does not fire the valuechanges
this.departmentUserControl.setValue(this.bar.SolvingUser);
}
This is a small sample of what my code is; StackBlitz
What am I doing wrong here?
You have 2 issues.
You have to add subscribe() to valueChanges.
You have to call this.mapObjects() after valueChanges.
this.filteredUserList = this.departmentUserControl.valueChanges.pipe(
startWith(""),
map(value => {
console.log("ToFilterValue =>>", value);
return typeof value === "string"
? this.filterUser(value)
: this.filterUser(value ? value.Name : "");
})
).subscribe();
this.mapObjects();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With