【问题标题】:Angular Material Input Textbox Wrapper to work with ControlValueAccessor and inner formControlNameAngular 材质输入文本框包装器与 ControlValueAccessor 和内部 formControlName 一起使用
【发布时间】:2020-03-23 19:30:03
【问题描述】:

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

目标是让这个程式化的文本框与表单一起使用。

打字稿:

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】:

    表单组没有从InputTextboxComponent 接收值的原因是因为没有在每次input 元素从用户接收到新值时调用onChange 方法。我为InputTextboxComponent 内的input 元素添加了一个更改事件侦听器,并从那里调用onChange 方法。 (input-text-box.component.ts 的第 58 行)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 2017-09-16
      • 2020-03-24
      • 2020-03-23
      • 1970-01-01
      相关资源
      最近更新 更多