[ngx-formly] Use 3rd party Form Controls with Angular Formly / Custom type

In a real form you‘ll most likely want to add some 3rd party form controls. For example autocomplete fields, date-time pickers etc. In this lesson we‘re going to see how to use ng-select and configure it s.t. it can be used within our Formly form.

customs/ng-select.typs.ts:

import { Component } from ‘@angular/core‘;
import { FieldType } from ‘@ngx-formly/core‘;

@Component({
  selector: ‘formly-ng-select‘,
  template: `
    <div class="mat-input-infix mat-form-field-infix">
      <ng-select
        [items]="to.options | async"
        [placeholder]="to.label"
        [bindValue]="to.bindValue || ‘value‘"
        [formControl]="formControl"
        [class.is-invalid]="showError"
      >
      </ng-select>
    </div>
  `,
})
export class NgSelectFormlyComponent extends FieldType {}

app.module.ts:

import { BrowserModule } from ‘@angular/platform-browser‘;
import { NgModule } from ‘@angular/core‘;

import { AppComponent } from ‘./app.component‘;
import { ReactiveFormsModule, FormControl, ValidationErrors } from ‘@angular/forms‘;
import { FormlyModule, FormlyFieldConfig } from ‘@ngx-formly/core‘;
import { FormlyMaterialModule } from ‘@ngx-formly/material‘;
import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations‘;
import { NgSelectModule } from ‘@ng-select/ng-select‘;

import { SharedModule } from ‘./shared/shared.module‘;
import { NgSelectFormlyComponent } from ‘./customs/ng-select.type‘;

// global min error message, you can override by validation.messages.min in field
export function minValidationMessage(err, field: FormlyFieldConfig) {
  return `Please provide a value bigger than ${err.min}. You provided ${err.actual}`;
}

export function ipValidationMessage(err, field: FormlyFieldConfig) {
  return `"${field.formControl.value}" is not a valid IP address`;
}

export function IpValidator(control: FormControl): ValidationErrors {
  return !control.value || /(\d{1,3}\.){3}\d{1,3}/.test(control.value) ? null : { ip: true };
}

@NgModule({
  declarations: [AppComponent, NgSelectFormlyComponent],
  imports: [
    BrowserModule,
    SharedModule,
    NgSelectModule,
    ReactiveFormsModule,
    FormlyModule.forRoot({
      validators: [
        {
          name: ‘ip‘,
          validation: IpValidator,
        },
      ],
      validationMessages: [
        {
          name: ‘required‘,
          message: ‘This field is required‘,
        },
        {
          name: ‘min‘,
          message: minValidationMessage,
        },
        {
          name: ‘ip‘,
          message: ipValidationMessage,
        },
      ],
      types: [
        {
          name: ‘my-autocomplete‘,
          component: NgSelectFormlyComponent,
        },
      ],
    }),
    FormlyMaterialModule,
    BrowserAnimationsModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

app.component.ts:

    {
      key: ‘nationId‘,
      type: ‘my-autocomplete‘,
      templateOptions: {
        label: ‘Nation‘,
        options: this.dataService.getNations(),
      },
    },

原文地址:https://www.cnblogs.com/Answer1215/p/12173001.html

时间: 2024-09-30 20:40:53

[ngx-formly] Use 3rd party Form Controls with Angular Formly / Custom type的相关文章

Angular5 错误: ngModel cannot be used to register form controls with a parent formGroup directive

在创建一个表单时,出现了这样的错误: 原因是,在最外层的form中使用了 formGroup 指令,但在下面的某个input 插件中,使用了ngModel 指令,但没有加入formControl 指令或 formControlName 属性. 1 <form [formGroup]="form"> 2 <mat-form-field> 3 <input matInput placeholder="IP(SNMP)" [formContr

form表单重复提交,type=“button”和type=“submit”区别

公司测试提了一个项目后台在IE浏览器下(360,firefox就没问题)出现数据重复的问题,调试了好久终于发现问题所在,也不知道是谁写的代码,醉醉的.... 错误地点: <input type="submit" value="提交"  class="btn"  id="formSubmit" onclick="checkForm()"  /> type类型写成submit,而在checkForm

Django - Form嵌套的Meta类 + 为什么type()能创建类

Form里面嵌套了一个Meta类 class PostForm(forms.ModelForm): class Meta: model = Post # field to be exposed fields = ('title', 'text') Django是怎么处理的? 在models.py中 def modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, wid

来自 Thoughtram 的 Angular 2 系列资料

Angular 2 已经正式 Release 了,Thoughtram 已经发布了一系列的文档,对 Angular 2 的各个方面进行深入的阐释和说明. 我计划逐渐将这个系列翻译出来,以便对大家学习 Angular 2 提供一些方便. Getting Started Building a Zippy component in Angular 2 Developing a Tabs component in Angular 2 Angular 2 Template Syntax demystifi

两个form之间传递数据

Passing Data Between Forms FormData.dpr --------------------------------------------------------- program FormData; uses  Forms,  IWMain,  ServerController in 'ServerController.pas' {IWServerController: TDataModule},  Main in 'Main.pas' {formMain: TI

HTML表单(Form)

HTML表单(Form)是HTML的一个重要部分,主要用于采集和提交用户输入的信息. 举个简单的例子,一个让用户输入姓名的HTML表单(Form).示例代码如下: <form action="http://www.admin5.com/html/asdocs/html_tutorials/yourname.asp" method="get"> 请输入你的姓名: <input type="text" name="your

Overview of Form Control Types [AX 2012]

Overview of Form Control Types [AX 2012] Other Versions 0 out of 1 rated this helpful - Rate this topic Updated: October 11, 2011 Applies To: Microsoft Dynamics AX 2012 R3, Microsoft Dynamics AX 2012 R2, Microsoft Dynamics AX 2012 Feature Pack, Micro

实现点击Form区域内除ListBox以外的其他地方,实现ListBox的隐藏,包括UserControl范围内,也包括UserControl之外Form之内

const int WM_PARENTNOTIFY = 0x210; const int WM_LBUTTONDOWN = 0x201; protected override void WndProc(ref Message m) { if (m.Msg == WM_LBUTTONDOWN || (m.Msg == WM_PARENTNOTIFY && (int)m.WParam == WM_LBUTTONDOWN)) { if (tab.SelectedForm is Form) { F

@angular/cli项目构建--Dynamic.Form

导入所需模块: ReactiveFormsModule DynamicFormComponent.html <div [formGroup]="form"> <label [attr.for]="formItem.key">{{formItem.label}}</label> <div [ngSwitch]="formItem.controlType"> <input *ngSwitchCas