Below is an Angular form group that I need help with. My goal is to initialize the form and if there is no data coming into the Input() data
property, then set the form values as empty strings ''
for user input. However, if there is indeed form data coming in through the data
property, I want to initialize the form and have it pre-populate with the incoming data. Currently, I am using the setValue
method but it feels repetitive to repeat much of the initialization code. Is there a more elegant solution?
@Component({...})
export class SignupFormComponent implements OnInit {
Input(): data;
user: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.user = this.fb.group({
name: ['', [Validators.required, Validators.minLength(2)]],
email: ['', Validators.required]
});
}
if(this.data) {
this.user.setValue({
name: this.data.name,
email: this.data.email
})
}
}