【问题标题】:FormControl ValueChanges Pipe Not FiringFormControl ValueChanges 管道未触发
【发布时间】:2021-01-06 10:28:22
【问题描述】:

如果组件具有input 值,我需要更新组件。这样做时,我正在设置通常通过将文本插入input 并从autocomplete 中选择列表值来设置的值。即使我将object 设置为FormControl 变量,valueChangespipe 也不会这样看。但我确信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>

这是我放入ngOninitvalueChanges 管道;

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


    【解决方案1】:

    您有 2 个问题。

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

    2. 您必须在valueChanges 之后调用this.mapObjects()

        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();
    

    【讨论】:

    • 我怎么会错过mapObjects() location :D 谢谢你的帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2017-09-18
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    相关资源
    最近更新 更多