display form array on selection of dropdwon in angular

空扰寡人 提交于 2021-02-11 06:52:02

问题


I have a form with following fields: name (textbox), category(dropdown). I want to display a formarray textbox with an add option on selection of dropdwon="3". When i click "add new textfields", new textboxes should be added.

Right now i'm showing a textbox (listitem) after selection of dropdown="3". and then on addnewtextfield i'm calling a formarray.

Please help me acheive the functionality. Thanks in advance.

Updated code in Stackblitz: https://stackblitz.com/edit/angular-ivy-js8tfp?file=src%2Fapp%2Fapp.component.html

<form [formGroup]="addForm" (ngSubmit)="onSubmit()">

    <input type="text" class="form-control" placeholder="enter term"
                          formControlName="name">
    <small class="errormessage" *ngIf="submitted && addForm.controls.name.hasError('required')">
                            Term is required
                          </small>


    <select class="Dropdown" formControlName="category">
                            <option value="undefined" selected disabled >Select Category</option>
                            <option  *ngFor="let list of dropdownitems" [value]="list.id" >{{list.name}}</option>
                        </select>

    <small class="errormessage" *ngIf="submitted && addForm.controls.category.hasError('required')">
                            Category is required 
                        </small>


    <ng-container *ngIf="showOptions">

        <input type="text" formControlName="listItem" class="form-control" placeholder="enter dropdownlist items">
        <small class="errormessage" *ngIf="submitted && addForm.controls.listItem.hasError('required')">
                            Category is required 
                        </small>
        <a (click)="addGroup()">Add New Textfield</a>

    </ng-container>
  <!---see how use formArray-->
  <ng-container formArrayName="times">
    <span  *ngFor="let time of timesArray.controls; let i = index;">
                      <span [formGroupName]="i">                         
                            <input type="text" class="form-control" formControlName="lists" placeholder="enter dropdown options">  

                      </span>
    <a (click)="removeGroup(i)">Remove Textfield</a>
    </span>
  </ng-container>

    <input type="Submit" class="savebtn" Value="Save" Style="width: 100px;"/>&nbsp;

</form>
<pre>{{addForm?.value|json}}</pre>

export class AppComponent  {
  name = 'Angular ' + VERSION.major;

  addForm: FormGroup;
  submitted = false;
  showOptions: any;

  public dropdownitems = [{
    name: "A",
    id: 1
  },{
    name: "B",
    id: 2
  },{
    name: "C",
    id: 3   
  },{
    name: "D",
    id: 4    
  }]

//ADD this getter
 get timesArray()
 {
   return this.addForm.get('times') as FormArray
 }
 constructor(
    private formBuilder: FormBuilder,
    ) { }

 ngOnInit(): void {
    this.addForm = this.formBuilder.group({
      name: ['', [Validators.required, Validators.pattern('[a-zA-Z# ]*')]],
      category: ['', [Validators.required]],
      listItem: ['', [Validators.required]],
      status: ['Y', [Validators.required]] ,
      times: this.formBuilder.array([])
      }); 

      this.addForm.get("category").valueChanges.subscribe((category) => {
        
    if(category === '3') {
      this.showOptions = true;
         this.addForm.get("listItem").enable();
    } else {
      this.showOptions = false;
         this.addForm.get("listItem").disable();
    }
});

  }

  onSubmit(){
     //   console.log(this.addForm.controls['category'].value)
    this.submitted = true;
    if (this.addForm.invalid) {
      alert ('Please fill up complete details');
      return;
    }
    console.log(this.addForm.value);   
}


value = this.formBuilder.group({
  lists: ['', Validators.required],
});


addGroup() {
  if (this.addForm.get('listItem').invalid)
  {
     alert ("fill the term field")
     this.addForm.get('listItem').updateValueAndValidity()
     return;
  }
  if (this.timesArray.invalid)
  {
     alert ("fill the items field")
     this.timesArray.updateValueAndValidity()
     return;

  }
  const val = this.formBuilder.group({
    lists: ['', Validators.required],
  });
  const form = this.addForm.get('times') as FormArray;
  form.push(val);
}

removeGroup(index) {
  const form = this.addForm.get('times') as FormArray;
  form.removeAt(index);
}



}

来源:https://stackoverflow.com/questions/66134235/display-form-array-on-selection-of-dropdwon-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!