mat-select 中的 selected 值未发送给父级

The selected value in a mat-select is not sent to parent

我在 angular 库中创建了一个下拉列表以用于我们的应用程序。我使用 angular-material2 作为下拉菜单(mat-select 和 mat-autocomplete)。

我一定是做错了什么,因为我在应用程序中使用下拉菜单时没有得到值。我已经尝试了几乎所有我在网上找到的东西,但没有结果。

我对其中的大部分内容进行了评论,我正在尝试解决最简单的问题,但即使在这种情况下,我也没有获得价值。这是我现在拥有的:

DropdownComponent.html图书馆:

<mat-form-field appearance="outline">
    <mat-select disableOptionCentering (selectionChange)="writeValue($event)" [multiple]="multi">
      <mat-option *ngFor="let item of list" [value]="item">
        {{ item }}
      </mat-option>
    </mat-select>
</mat-form-field>

DropdownComponent.ts图书馆:

import {Component, OnInit, ViewEncapsulation, Input, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl} from '@angular/forms';
import {Observable} from 'rxjs';

@Component({
  selector: 'pux-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss'],
  encapsulation: ViewEncapsulation.None,
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DropdownComponent), multi: true },
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => DropdownComponent), multi: true }
  ]
})
export class DropdownComponent implements OnInit, ControlValueAccessor {
  @Input() list: any[] = [];
  @Input() selected: any;
  @Input() multi = false;
  @Input() search = false;
  items: any[] = [];
  propagateChange = (_: any) => {};
  validateFn: any = () => {};

  constructor() { }

  ngOnInit() {
    this.items = this.list;
  }

  // Form

  get value(): any { return this.selected; }
  set value(newValue: any) {
   if (newValue !== this.selected) {
     this.writeValue(newValue);
     this.registerOnChange(newValue);
     this.selected = newValue;
    }
  }

  registerOnChange(fn: any): void { this.propagateChange = fn; }

  registerOnTouched(fn: any): void {}

  setDisabledState(isDisabled: boolean): void {}

  writeValue(obj: any): void {
    if (obj !== null) {
      this.selected = obj.value;
      this.registerOnChange(this.selected);
      console.log(this.selected);
    }
  }

  validate(c: FormControl) { return this.validateFn(c); }
}

DropDownComponent.html申请:

<div>
    <form [formGroup]="selectForm" (ngSubmit)="saveSelect(selectForm)" #form1="ngForm">
        <div>
            <pux-dropdown formControlName="selectValue" [list]="list1"> </pux-dropdown>
        </div> <br>
        <button mat-flat-button="primary" type="submit" class="btn btn-primary">Save</button>
    </form> <br>
    <div>
         Saved Value: {{selectValue | json}}
    </div>
</div>

DropdownComponent.ts申请:

import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder} from '@angular/forms';

const states = [
  'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware',
  'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky',
  'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi',
  'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico',
  'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania',
  'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
  'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent implements OnInit {
  list1;
  multi: boolean;
  selected: any;
  search: boolean;
  // Form
  selectForm: FormGroup;
  selectValue: string;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.list1 = states;
    // Form
    this.selectForm = this.fb.group({
      selectValue: this.selected
    });
  }

  saveSelect(formValues) {
    console.log(formValues.value.selectValue);
    this.selectValue = formValues.value.selectValue;
  }
}

库中 writeValue 中的 console.log 在下拉列表中为我提供了 select 的值,但 saveSelect 中的 console.log 显示为空。因此该值不会发送给父级。知道我做错了什么吗?提前谢谢你。

您的 writeValue 实现需要调用更改函数,但它调用的是 registerOnChange 函数,该函数供表单控件注册其更改函数。尝试这样的事情:

propagateChange: (value: any) => void = () => {};

registerOnChange(fn: (value: any) => void) { this.propagateChange = fn; }

writeValue(obj: any): void {
  if (obj !== null && obj !== this.selected) {
    this.selected = obj.value;
    this.propagateChange(this.selected);
  }
}