C0mpl3x
C0mpl3x

Reputation: 532

How to add form control to specific control

How do I add new form control or form group to specific form control?

public SaleRequestForm: FormGroup = new FormGroup({
        SaleToPOIRequest: new FormGroup({
          MessageHeader: new FormGroup({
            MessageType: new FormControl(''),
            MessageClass: new FormControl(''),
            MessageCategory: new FormControl(''),
            SaleID: new FormControl(''),
            POIID: new FormControl(''),
            ProtocolVersion: new FormControl(''),
            ServiceID: new FormControl(''),
          })
    })

I image it would look something like this.

this.SaleRequestForm.controls.MessageHeader.addControl('test', new FormControl());

I've been googling and googling but I can't seem to find an answer

Upvotes: 0

Views: 308

Answers (2)

Random
Random

Reputation: 3236

I would do it step by step:

const saleToPOIRequest: FormGroup = this.SaleRequestForm?.get("SaleToPOIRequest") as FormGroup;
const messageHeader: FormGroup = saleToPOIRequest?.get("MessageHeader") as FormGroup;
if (messageHeader) {
  const myNewFormControl = new FormControl(null);
  messageHeader.addControl("foo", myNewFormControl);
}

Upvotes: 0

Gabriel Sereno
Gabriel Sereno

Reputation: 855

Your thought is right, but just will appear in angular if you cast the object with FormGroup, like this:

(this.SaleRequestForm.get("SaleToPOIRequest.MessageHeader") as FormGroup).addControl("test", new FormControl())

Stackblitz: https://stackblitz.com/edit/angular-ivy-jmvmdf?file=src/app/app.component.ts

Upvotes: 1

Related Questions