Created
January 9, 2020 13:01
-
-
Save hijiangtao/6f1ef59702b67c9bdb5e8f6d42ba725f to your computer and use it in GitHub Desktop.
[Angular] ControlValueAccessor with formGroup data in child component
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, Input} from '@angular/core' | |
import { | |
FormControl, | |
FormGroup, | |
ControlValueAccessor, | |
NG_VALUE_ACCESSOR, | |
FormBuilder, | |
Validator | |
} from '@angular/forms'; | |
@Component({ | |
selector: 'my-child', | |
template: ` | |
<h1>Child</h1> | |
<div [formGroup]="name"> | |
<input formControlName="firstName"> | |
<input formControlName="lastName"> | |
</div> | |
`, | |
providers: [ | |
{provide: NG_VALUE_ACCESSOR, useExisting: Child, multi: true} | |
] | |
}) | |
export class Child implements ControlValueAccessor { | |
name: FormGroup; | |
constructor(fb: FormBuilder) { | |
this.name = fb.group({ | |
firstName:[''], | |
lastName: [''] | |
}); | |
} | |
writeValue(value: any) { | |
if(value) { | |
this.name.setValue(value); | |
} | |
} | |
registerOnChange(fn: (value: any) => void) { | |
this.name.valueChanges.subscribe(fn); | |
} | |
registerOnTouched() {} | |
} |
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, Input} from '@angular/core' | |
import { | |
FormControl, | |
FormGroup, | |
ControlValueAccessor, | |
NG_VALUE_ACCESSOR, | |
FormBuilder, | |
Validator | |
} from '@angular/forms'; | |
@Component({ | |
selector: 'my-app', | |
template: ` | |
<div> | |
<h4>Hello {{name}}</h4> | |
<form [formGroup]="form" (ngSubmit)="sayHello()"> | |
<input formControlName="name"><br> | |
<input formControlName="email"><br> | |
<my-child formControlName="username"></my-child> | |
<button type="submit">Register</button> | |
</form> | |
{{form.value | json }} | |
</div> | |
` | |
}) | |
export class App { | |
form: FormGroup; | |
constructor(fb: FormBuilder) { | |
this.form = fb.group({ | |
name:['Angular2 (Release Candidate!)'], | |
username: [{firstName: 'First', lastName: 'Last'}], | |
email:['My Email'] | |
}); | |
} | |
sayHello() { | |
console.log(this.form.value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@MaratMartirosyan999 @sayeduzzamancuet @hknozturk
Looks like creating empty
registerOnChange(fn: Function): void
solves the issue