Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormControl ValueChanges Pipe Not Firing

Tags:

angular

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?

like image 884
oividiosCaeremos Avatar asked Apr 22 '26 19:04

oividiosCaeremos


1 Answers

You have 2 issues.

  1. You have to add subscribe() to valueChanges.

  2. 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();
like image 155
N.F. Avatar answered Apr 24 '26 08:04

N.F.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!