首页 > 解决方案 > FormControl ValueChanges 管道未触发

问题描述

input如果组件有值,我需要更新组件。这样做时,我正在设置通常通过将文本插入input并从 中选择列表值来设置的值autocomplete。即使我将 an 设置objectFormControl变量,valueChanges管道也不会那样看。但我确信它formControl得到了值,因为在前端我显示数据,formControl.value ? formControl.value.Name : ''并且在我的情况下,表单控件的输入中有一个合法的名称。

这就是我显示数据的方式;

<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>

这是我valueChanges放入的管道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 : '')
  })
);

如果有值,这就是我更新值的方式;(这个函数在 valueChanges 管道声明之前在 ngOnInit 内部被调用)

mapObjects(){
    // does not fire the valuechanges
    this.departmentUserControl.setValue(this.bar.SolvingUser);
}

这是我的代码的一个小示例; StackBlitz

我在这里做错了什么?

标签: angular

解决方案


你有2个问题。

  1. 您必须添加subscribe()valueChanges.

  2. 你必须在this.mapObjects()之后打电话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();

推荐阅读