Rohith V
Rohith V

Reputation: 1123

Dynamically adding new text box after button press is not working - Angular

I am creating an Edit Employee form and there is a button Add new skill which need to create new text box to add the skill. The sample output

But when I click on Add new skill, it is not adding any new text boxes and displaying these details inside the console.

Console

My typescript code :

import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, NgForm, Validators } from '@angular/forms';
import { EmployeeDepartment } from '../employee-department-class';


@Component({
  selector: 'app-edit-emp-form-builder',
  templateUrl: './edit-emp-form-builder.component.html',
  styleUrls: ['./edit-emp-form-builder.component.css']
})
export class EditEmpFormBuilderComponent implements OnInit {

  /**
   * Using some default values and may be different from other component
   */


  department = [
    new EmployeeDepartment(1, 'Payroll'),
    new EmployeeDepartment(2, 'Internal'),
    new EmployeeDepartment(3, 'HR')
  ]

  skills: any = []
  employeeDetails = this.fb.group({
    employeeName: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(20)]],
    department: [null, [Validators.required]],
    skills: this.fb.array([
      this.fb.control('')
    ])
  });
  constructor(private fb: FormBuilder) {

  }

  get skill() {
    return this.employeeDetails.get('skills') as FormArray;
  }

  addSkill() {
    this.skills.push(this.fb.control(''));
  }

  onSubmit(f: NgForm) {
    console.log(f);
  }

  ngOnInit(): void {
  }

}

My HTML code for the skill

 <div formArrayName="skills">
    <h3>Skill</h3>
    <button (click)="addSkill()">Add new skill</button>
    <div *ngFor="let s of skill.controls; let i = index">
      <label>Skill:
        <input type="text" [formControlName]="i">
      </label>
    </div>

  </div>

Upvotes: 0

Views: 446

Answers (1)

Abdu Manas C A
Abdu Manas C A

Reputation: 1139

Remove the variable skills: any = [] from your code.
Rename get skill() to get skills()

Upvotes: 1

Related Questions