Angular Material Input Textbox Wrapper与ControlValueAccessor和内部formControlName一起使用

问题描述 投票:1回答:1

我正在尝试让ControlValueAccessor和formControlName与客户的Material Input Textbox一起使用。由于某种原因,代码无法正常工作,并尝试对其进行修复。阅读大量教程,并应用ControlValueAccsor。我们应该使用MAT_INPUT_VALUE_ACCESSOR吗?用材料角最简单的解决方法是什么?

目标是使该样式化文本框与Forms一起使用。

Typescript:

import { Component, OnInit, Input, ViewChild, EventEmitter, Output, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-input-textbox',
  templateUrl: './input-textbox.component.html',
  styleUrls: ['./input-textbox.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputTextboxComponent),
      multi: true
    }
  ]
})

export class InputTextboxComponent implements OnInit, ControlValueAccessor {
  @Input() MaxLength: string;
  @Input() Disabled: boolean;
  @Input() ReadOnly: boolean;
  @Input() NgClass:string;
  @Input() Value: string;
  @Input() type: string;
  @Input() Label: string;
  @Input() PlaceHolder: string;
  @Output() saveValue = new EventEmitter();
  @Output() onStateChange = new EventEmitter();

  disabled: boolean;

  constructor() { }

  ngOnInit() {
  }

  saveValueAction(e) {
    this.saveValue.emit(e.target.value);
  }

  onChange(e) {
    this.Value = e;
  }

  onTouched() {
    this.onStateChange.emit();
  }

  writeValue(value: any) {
    this.Value = value ? value : '';
  }

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

  registerOnTouched(fn: any) { this.onTouched = fn; }

  setDisabledState(isDisabled) { this.disabled = isDisabled; }
}

HTML:

<div class="input-wrap">
    <mat-form-field appearance="outline">
        <mat-label>{{Label}}</mat-label>   
        <input matInput 
            [attr.maxlength] = "MaxLength"
            [value]="Value ? Value : ''"
            [placeholder]="PlaceHolder ? PlaceHolder : ''"
            [readonly]="ReadOnly"
            [ngClass]="NgClass"
            [type]="type ? type: 'text'"
        >
    </mat-form-field>
</div>
angular typescript angular-material angular7
1个回答
1
投票

表单组未从InputTextboxComponent接收值的原因是因为每次onChange元素从用户接收新值时,都不会调用input方法。我为input中的InputTextboxComponent元素添加了一个变化事件侦听器,并从那里调用了onChange方法。 (input-text-box.component.ts的第58行)

示例:https://stackblitz.com/edit/angular-h4ebkp

© www.soinside.com 2019 - 2024. All rights reserved.