[Angular2 Form] Create custom form component using Control Value Accessor

//switch-control component 

import { Component } from ‘@angular/core‘;
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, Validators} from ‘@angular/forms‘;

@Component({
  selector: ‘switch-control‘,
  templateUrl: ‘./switch-control.component.html‘,
  styleUrls: [‘./switch-control.component.css‘],
  providers: [
    {provide: NG_VALUE_ACCESSOR, multi: true, useExisting: SwitchControlComponent}
  ]
})
export class SwitchControlComponent implements ControlValueAccessor {
  isOn: boolean;
  _onChange: (value: any) => void;

  writeValue(value: any) {
    this.isOn = !!value;
  }

  registerOnChange(fn: (value: any) => void) {
    this._onChange = fn;
  }

  registerOnTouched() {}

  toggle(isOn: boolean) {
    this.isOn = isOn;
    this._onChange(isOn);
  }
}

The writeValue function allows you to update your internal model with incoming values, for example if you use ngModel to bind your control to data.

The registerOnChange accepts a callback function which you can call when changes happen so that you can notify the outside world that the data model has changed. Note that you call it with the changed data model value.

The registerOnTouched function accepts a callback function which you can call when you want to set your control to touched. This is then managed by Angular 2 by adding the correct touched state and classes to the actual element tag in the DOM.

Using it:

    this.signupForm = fb.group({
      password: [
        ‘‘,
        Validators.required
      ],
      confirm: [
        ‘‘,
        [
          Validators.required,
          confirmPasswords.bind(undefined, this.signup)
        ]
      ],
      newsletter: true
    });
<form novalidate autocomplete="off" [formGroup]="signupForm">
  <div class="form-field">
    <label>Password:</label>
    <input type="text" formControlName="password" [(ngModel)]="signup.password" name="password">
  </div>
  <div class="form-field">
    <label>Confirm Password: </label>
    <input type="text" formControlName="confirm" [(ngModel)]="signup.confirm" name="confrim">
    <div *ngIf="!signupForm.valid">
      <span *ngIf="signupForm.get(‘confirm‘).hasError(‘confirmPassword‘) && signupForm.get(‘confirm‘).touched">
        {{signupForm.get(‘confirm‘).errors?.confirmPassword.message}}
      </span>
      <span *ngIf="signupForm.get(‘confirm‘).hasError(‘required‘) && signupForm.get(‘confirm‘).dirty">This field is requred</span>
    </div>
    <switch-control formControlName="newsletter"></switch-control>
  </div>
</form>

Here in the code we set the default value to be true thought "writeValue" method handle by angular2, also we get updated value from the component thought "registonChange" method.

Link: http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel

Github: https://github.com/kara/ac-forms/tree/master/src/app/switch-control

时间: 2024-10-10 01:06:33

[Angular2 Form] Create custom form component using Control Value Accessor的相关文章

[Angular2 Form] Model Driven Form Custom Validator

In this tutorial we are going to learn how simple it is to create custom form field driven validators while using Angular 2 model driven forms. These type of validators are really just plain functions that follow a set of conventions. We are going to

Create Custom Modification Form In VS 2012-Part2

1.SPWorkflowModification ContextData is XMLSerialized as String. 2.Get SPWorkflowModification ContextData in modification page protected void GetContexData()        {            SPWeb currentWeb = SPContext.Current.Web;            string strWorkflowI

Create Custom Modification Form In VS 2012-Part1

Step1.Add EventHandlingScope Activity Under OnWorkflowActivated Step2.Add SequenceActivity In EventHandlingScope Activity Step3.Add EnableWorkflowModification Activity a.Bind [ContextData] to a new field b.Set [Colorrelation Token] as "Modification&q

[Angular] Adding keyboard events to our control value accessor component

One of the most important thing when building custom form component is adding accessbility support. The component should be focusable. we can achieve this by adding 'tabindex="0"': <div tabindex="0" > Add some css class for foucs

UE4 Tutorial - Custom Mesh Component

UE4 Tutorial - Custom Mesh Component Over the last few weeks I've been working on an old idea that I had and ended up starting from scratch. In my research I ended up finding the "Custom Mesh" component. This is a great component that can be use

$(#form&#160;:input)与$(#form&#160;input)的区别

相信大家都很奇怪这两者的区别 我从两个方面简单介绍下 1. $("form :input") 返回form中的所有表单对象,包括textarea.select.button等    $("form input")返回form中的所有input标签对象 2. form input 是属于层级选择器(将每一个选择器匹配到的元素合并后一起返回)   form :input是属于表单选择器(匹配所有input,textarea,select,button等)

delphi form.hide和form.visiable 失效?

后来我发现form.hide和form.visiable 全部失效了,然后用 ShowWindow(Application.Handle, SW_HIDE);   ShowWindow(Application.MainFormHandle, SW_HIDE);

[转]How to Create Custom Filters in AngularJs

本文转自:http://www.codeproject.com/Tips/829025/How-to-Create-Custom-Filters-in-AngularJs Introduction Filter in Angular JS is a way that will help you to represent your data in View in a certain format. There are many inbuilt filters provided by Angular

关于$(&quot;form&quot;).serializeObject()与$(&quot;form&quot;).serialize()

form.serialize():jQuery的serialize()方法通过序列化表单值,可以把序列化的值传给ajax()作为url的参数,轻松使用ajax()提交form表单了,而不需要一个一个获取表单中的值然后传给ajax() form.serializeObject():讲form表单转成javasrcipt object对象,将form里面的内容转化成json格式 例:{ "a":1, "b":2, "c":3 } 拓展:(1)将表单序