How to dynamically set Angular form data

1.5k views Asked by At

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
    })
  }
}
2

There are 2 answers

0
V.Tur On

Angular make this action more simply:

@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(this.data) //no need set values separately
  }
}
0
Developer On

Checkout Demo here into this Stackblitz Link

You can basically need only set data directly to control, for very first time initialization.

@Input() data;
form: FormGroup;

constructor(private fb: FormBuilder) { }

ngOnInit() {
   this.form = this.fb.group ({
     nameCtr: [{value :this.data?.dataName || '', disabled: false}]
})
 

If data property is set then it will set default data from property, else it assign default to empty string.