垫选中的所选值不会发送给父级

时间:2018-07-03 12:05:17

标签: angular-material2 angular6 angular-library controlvalueaccessor

我在角度库中创建了一个下拉列表,供我们的应用程序使用。我将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为我提供了我在下拉列表中选择的值,但是saveSelect中的console.log向我显示了null。因此,该值不会发送给父级。知道我在做什么错吗?预先谢谢你。

1 个答案:

答案 0 :(得分:1)

您的writeValue实现需要调用change函数,但是它正在调用registerOnChange函数,表单控件可以在那里注册其change函数。尝试这样的事情:

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