I have an Angular form group below. What I want to do is simple, initialize the form and if there is not data coming into the Input() data
property, then set the form values as emtpy string ''
ready for input from user. However, if there is form data coming in via the data
property, then I want to initialize the form but have it pre-populate from the data from input property. I'm using the setValue
method, but it doesn't seem very elegant. It looks like I'm repeating a lot of the initialization code. Is there a better way?
@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
})
}
}
Angular make this action more simply: