Last active
July 26, 2016 02:14
-
-
Save iamssen/b4a4dc646df824ee25c7c2cf58805b8d to your computer and use it in GitHub Desktop.
Angular2 Custom Form Component. (@angular - 2.0.0-rc.4, @angular/forms - 0.2.0)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component, Provider, forwardRef} from '@angular/core'; | |
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from '@angular/forms'; | |
@Component({ | |
selector: 'custom-form-component', | |
template: `<div (click)="onClick()">{{value}}</div>`, | |
styles: [` | |
div { | |
border: 1px solid black; | |
background-color: #eeeeee; | |
padding: 5px; | |
cursor: pointer; | |
} | |
`], | |
providers: [ | |
new Provider(NG_VALUE_ACCESSOR, { | |
useExisting: forwardRef(() => AngularFormModelCustomComponent), | |
multi: true | |
}) | |
], | |
}) | |
export class AngularFormModelCustomComponent implements ControlValueAccessor { | |
private value:string = '-'; | |
private change:(newValue) => void; | |
private _name:string; | |
get name():string { | |
return this._name; | |
} | |
set name(value:string) { | |
this._name = value; | |
} | |
writeValue(obj:any):void { | |
this.value = obj ? obj.toString() : '-'; | |
} | |
registerOnChange(fn:any):void { | |
this.change = fn; | |
} | |
registerOnTouched(fn:any):void { | |
} | |
private onClick() { | |
this.value = 'random text... ' + Math.round(Math.random() * 1000); | |
if (this.change) this.change(this.value); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="form-group"> | |
<label>Custom</label> | |
<custom-form-component formControlName="custom"></custom-form-component> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="form-group"> | |
<label>Custom</label> | |
<custom-form-component name="custom" [(ngModel)]="data.custom"></custom-form-component> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment