【问题标题】:How to preselect options within a multi or single mat-select that relies on an Input() value?如何在依赖于 Input() 值的多个或单个 mat-select 中预选选项?
【发布时间】:2021-04-24 01:10:58
【问题描述】:

我创建了这个可重复使用的选择搜索组件。该组件可以具有预选项目。如果组件传递了一组预选选项,那么它应该预选它们。

目前,当我传递一个项目以预选它时,它会正确地将其添加到表单控件中,但是它不能正确显示。

我有另一个 Input(),称为 extractValue,用户可以在其中传递应该为选项显示的键值。

我试过compareWith函数来拉取显示值。此 compareWith 函数在任何 Inputs() 完全加载之前运行。所以extractValue 是未定义的。如果我硬编码这个值,它似乎仍然不能解决我的问题。

为什么表单控件设置值没有反映在 UI 中?

这是我的代码 ---> https://stackblitz.com/edit/angular-mat-select-multi-with-formcontrol-klabfl?file=app/select-search-dropdown.component.html

【问题讨论】:

    标签: angular angular-material angular-reactive-forms


    【解决方案1】:

    找到了您的compareWith 函数的原因,它无法获得extractValue,因为您的函数中this 的范围是mat-select,并且您的extractValue 的实际值存在于您的@987654326 中主要组件的@。

    我没有找到任何东西,这将允许我们传递您的父组件的范围。但作为一种解决方法,您可以执行以下操作:

    1. 在您的 selectSearchForm 中传递 extractValue。
    2. 然后,使用:this._parentFormGroup.value.extractValue; 访问它,并在您的 compareFn 中进行相应更改。

    以下是代码更改和工作stackblitz

    private _setUpFormControls(
        validators?: ISelectSearchValidators[],
        selected?: any,
        setInitialValue?: boolean,
        multiple?: boolean
      ): void {
        debugger;
        this.selectSearchForm = this._formBuilder.group({
          SelectControl: [
            this._setInitialValue(selected, setInitialValue, multiple),
            this._getValidatorFns(validators)
          ],
          SearchControl: [""],
          extractValue: this.extractValue
        }); 
      }
    
    compareFn(optionOne: any, optionTwo: any): boolean {
        const extractValue = this._parentFormGroup.value.extractValue;
        if (typeof optionOne === "string" && typeof optionTwo === "string") {
          return optionOne === optionTwo;
        } else if (!!optionOne[extractValue] && !!optionTwo[extractValue]) {
          return optionOne[extractValue] === optionTwo[extractValue];
        }
      }
    

    【讨论】:

    • 谢谢!看来这只是因为它找不到 _parentFormGroup 所以这个函数实际上并没有做任何事情。我切换了逻辑以检查 optionOne 和 optionTwo 对象是否与下划线相同。如果您编辑答案以使用它,我会接受它。预选项目似乎不适用于单选,但它确实适用于多选。
    猜你喜欢
    • 2019-04-28
    • 2020-11-29
    • 2022-08-18
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    相关资源
    最近更新 更多