Angular 10: 在Angular Material自定义表单字段控件中访问NgControl
创始人
2024-10-15 07:31:30
0

您可以使用ControlValueAccessor接口来自定义Angular Material表单字段控件,并在其中访问NgControl。以下是一个示例解决方案:

首先,创建一个自定义表单字段控件组件,实现ControlValueAccessor接口:

import { Component, forwardRef, Input, OnInit, Provider } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NgControl } from '@angular/forms';

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: Provider = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => CustomFormFieldComponent),
  multi: true
};

@Component({
  selector: 'app-custom-form-field',
  template: `
    
      
    
  `,
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomFormFieldComponent implements ControlValueAccessor, OnInit {
  @Input() placeholder: string;
  @Input() disabled: boolean;

  value: any;
  onChange: any = () => {};
  onTouched: any = () => {};

  constructor(private ngControl: NgControl) {}

  ngOnInit() {
    // 注册控件访问器
    this.ngControl.valueAccessor = this;
  }

  writeValue(value: any) {
    this.value = value;
    this.onChange(value);
    this.onTouched();
  }

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

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

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

然后,在使用该自定义表单字段控件的父组件中,您可以通过ViewChild装饰器访问NgControl

import { Component, OnInit, ViewChild } from '@angular/core';
import { NgControl } from '@angular/forms';
import { CustomFormFieldComponent } from './custom-form-field.component';

@Component({
  selector: 'app-parent-component',
  template: `
    
    
  `
})
export class ParentComponent implements OnInit {
  @ViewChild('customFormField', { static: true }) customFormField: CustomFormFieldComponent;

  constructor() {}

  ngOnInit() {}

  logNgControl() {
    console.log(this.customFormField.ngControl);
  }
}

在上面的示例中,我们通过ViewChild装饰器将CustomFormFieldComponent实例赋值给customFormField变量,并通过customFormField.ngControl访问NgControl实例。

这样,您就可以在自定义表单字段控件中访问NgControl实例,并执行需要的操作。

相关内容

热门资讯

最新通报!wepoker怎么设... 最新通报!wepoker怎么设置透视,德扑圈有透视吗,细节揭秘(有挂软件);实战中需综合运用上述技巧...
必看攻略!wpk辅助,wepo... 必看攻略!wpk辅助,wepoker辅助器下载,解说技巧(有挂辅助)是一款可以让一直输的玩家,快速成...
一分钟带你了解!aapoker... 一分钟带你了解!aapoker怎么拿好牌,aapoker辅助插件工具,线上教程(有挂透明)准备好在a...
我来分享!hhpoker可以控... 我来分享!hhpoker可以控制牌吗,德州局透视,辅助教程(有挂透视);大神普及一款德州ai内幕,确...
科技揭秘!约局吧app有挂吗,... 科技揭秘!约局吧app有挂吗,wepoker透视脚本网页,总结教程(有挂技巧);小薇(透视辅助)致您...
一起来讨论!hhpoker是正... 1、一起来讨论!hhpoker是正品吗,大菠萝免费辅助,wpk教程(有挂神器)。2、大菠萝免费辅助透...
推荐十款!aapoker发牌逻... 您好,佛手大菠萝有挂吗这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
玩家必看科普!wepoker买... 自定义wepoker买钻石有用吗系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅...
热点讨论!wepoker透视是... 热点讨论!wepoker透视是真的吗,wepoker手机版辅助,教你教程(有挂透视)1、点击下载安装...
我来教大家!wejoker黑侠... 我来教大家!wejoker黑侠辅助器,wepoker透视脚本免费使用视频,必赢方法(有挂透视);致您...