0

我没有使用 Formly,而是使用Angular Materialselect创建自己selectmat-selectselectionChange但是目前,当组件发生时,我很难获得新的价值custom-select

用于创建custom-select组件的 JSON:

...
{
  "key": "Q3",
  "type": "custom-select",
  "defaultValue": "-1",
  "templateOptions": {
    "order": "3",
    "optionsDynamic": "Q3",
    "child": "Q4",
    "label": "Foo",
    "onFocus": "this.focus(field)",
    "onChange": "this.onChangeQ(field)",
    "onBlur":"this.onBlur(field)",
    "valueProp": "id",
    "labelProp": "name"
  }
}
...

这就是我绑定onChange到的方式onChangeQ

if (f.templateOptions && f.templateOptions.onChange) {
  f.templateOptions.change = Function(
    'field',
    f.templateOptions.onChange
  ).bind(this);
}

这是我的custom-select.component.html

<mat-form-field appearance="outline">
    <mat-select 
        class="custom-select" 
        [formlyAttributes]='field'
        (selectionChange)="to.change(field)"
    >
        <mat-option 
            *ngFor="let option of field.templateOptions.options | async"
            [value]="option[field.templateOptions.valueProp]"
            [matTooltip]="option[field.templateOptions.labelProp]"
        >{{option[field.templateOptions.labelProp]}}</mat-option>
    </mat-select>
</mat-form-field>

这是我的custom-select.component.ts

import { Component } from '@angular/core';
import { FieldType } from '@ngx-formly/core';

@Component({
  selector: 'app-custom-select',
  templateUrl: './custom-select.component.html',
  styleUrls: ['./custom-select.component.css']
})
export class CustomSelectComponent extends FieldType {

  constructor() { super(); }
}

最后这是我的onChangeQ功能:

onChangeQ(field: FormlyFieldConfig) {
  console.log(field.formControl.value); 
  // field.formControl.value is always null 
  // eventhough field shows the exact field
  // which the change happened at.
}

我尝试使用setTimeOut,因为 Angular 有时需要它才能正常工作,但没有解决问题。而且我不能将MatSelectChange作为另一个参数发送到onChangeQ函数,因为最后会有许多自定义组件具有MatInputChangeMatRadioChange发送到函数,它们都有不同的路径来达到新值。

我如何使用它来使自己在selectionChange触发时达到新值?

4

0 回答 0