Form Array

נניח שיש לנו טופס שבו מכניסים פרטים אישיים ואנחנו רוצים שהמשתמש יכניס את שמות הילדים שלו. בהתחלה יופיע שדה אחד, והמשתמש יוכל להוסיף שדות כמספר שהוא צריך על ידי לחיצה על כפתור.

user.component.ts

constructor(private formBuilder: FormBuilder){}

public profileForm: FormGroup = new FormGroup({});

ngOnInit() {
    this.profileForm = this.formBuilder.group({
      userName: ['', Validation.required],
      children: this.formBuilder.array([])
    });
}

get children() : FormArray {
  return this.profileForm.get("children") as FormArray
}

אפשר גם ליצור קבוצה ולא רק פקד אחד.

user.component.ts

newChild(): FormGroup {
   return this.fb.group({
     name: '',
     age: 0,
   })
}

הוספת ילד חדש:

user.component.ts

addChild() {
   this.children.push(this.newChild());
}

הורדת שדה של ילד:

user.component.ts

removeChild(i:number) {
  this.children.removeAt(i);
}

onSubmit() {
   console.log(this.profileForm.value);
 }

נסדר את הטופס בטמפלט. יש לנו שני כפתורים אחד כדי להוריד שדה ואחד כדי להוסיף שדות נוספים לטופס.

user.component.html

<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
 
  <p>
    <label for="userName">Name </label>
    <input type="text" id="userName" name="userName" formControlName="userName">
  </p>

  <div formArrayName="children">
  <div *ngFor="let child of children().controls; let i=index">
      <div [formGroupName]="i">
        {{i}}
        Child name: <input type="text" formControlName="name">
        Age: <input type="number" formControlName="age">
 
        <button (click)="removeChild(i)">Remove</button>
      </div>
  </div>
</div>
 
 <p>
    <button type="submit">Submit</button>
  </p>
 
</form>

<p>
  <button type="button" (click)="addChild()">Add</button>
</p>
 
{{this.profileForm.value | json}}

ניווט במאמר

קומפוננטות - Components

Services

טפסים

Routes

Directives

Http Client

מאמרים אחרונים

Weekly Tutorial