Angular Reactive Forms Array - javascript

I am having problem accesssing products array located inside opticanOrders which is inside orderForm. In the console, I see that in order to access products array, I should reference it like that:
orderForm.controls.opticianOrders.controls.products.controls
But it doesn't work.
This is my component:
constructor(private customerService: CustomerService, private fb: FormBuilder) { }
orderForm: FormGroup;
ngOnInit() {
this.orderForm = this.fb.group({
name: [''],
surName: [''],
opticianOrders: this.fb.group({
orderDescription: [''],
products: this.fb.array([
this.initProduct()
])
}),
});
}
save(model: Customer) {
// call API to save customer
console.log(model);
}
onCancel(form: NgForm){
this.createState.emit(false);
}
initProduct(){
return this.fb.group({
name: [''],
manufacturerName: ['']
})
}
addProduct(){
const control = <FormArray>this.orderForm.controls['products'];
control.push(this.initProduct());
}
removeProduct(i: number){
const control = <FormArray>this.orderForm.controls['products']
}
Html
<form [formGroup]="orderForm" novalidate (ngSubmit)="save(orderForm)">
<!-- name -->
<div class="form-group">
<label>Name</label>
<input type="text" formControlName="name">
</div>
<!-- surName -->
<div class="form-group">
<label>Last Name</label>
<input type="text" formControlName="surName">
</div>
<div formGroupName="opticianOrders" class="form-group">
<label>Order Description</label>
<input type="text" formControlName="orderDescription">
</div>
<div formArrayName="products">
<div *ngFor="let product of orderForm.controls.opticianOrders.controls.products.controls; let i=index">
<div>
<span>Address {{i + 1}}</span>
<span *ngIf="orderForm.controls.opticianOrders.controls.products.controls.length > 1"
(click)="removeProduct(i)">
</span>
</div>
<div [formGroupName]="i">
<div>
<label>Product name</label>
<input type="text" formControlName="name">
</div>
</div>
</div>
</div>
<button type="submit" [disabled]="!orderForm.valid">Submit</button>
</form>

Please replace your HTML Code as per below
<form [formGroup]="orderForm" (ngSubmit)="save()">
<!-- name -->
<div class="form-group">
<label>Name</label>
<input type="text" formControlName="name">
</div>
<!-- surName -->
<div class="form-group">
<label>Last Name</label>
<input type="text" formControlName="surName">
</div>
<div class="form-group">
<label>Order Description</label>
<input type="text" formControlName="orderDescription">
</div>
<div formArrayName="products">
<div *ngFor="let product of orderForm.controls.products['controls']; let i=index">
<div>
<span><strong>Product {{i + 1}}</strong></span>
<span class="fa fa-times" *ngIf="orderForm.controls['products'].controls.length > 1" (click)="removeProduct(i)">
</span>
</div>
<div [formGroupName]="i">
<div>
<label>Product name</label>
<input type="text" formControlName="name">
</div>
<div>
<label>Product Manufacturer name</label>
<input type="text" formControlName="manufacturerName">
</div>
</div>
</div>
<div class="margin-20">
<a (click)="addProduct()" style="cursor: pointer; text-transform: uppercase; font-weight: 500">
Add another Entry +
</a>
</div>
</div>
<button class="btn btn-primary" type="submit" [disabled]="orderForm.invalid">Submit</button>
</form>
Please replace TS code as per below. I have used a trick in save form method, check whether it works for you or not?
constructor(private fb: FormBuilder) { }
orderForm: FormGroup;
ngOnInit() {
this.orderForm = this.fb.group({
name: ['', Validators.required],
surName: ['', Validators.required],
orderDescription: ['', Validators.required],
products: this.fb.array([
this.initProduct()
])
});
}
save() {
console.log(this.orderForm.value);
const obj = {
name: this.orderForm.value.name,
surName: this.orderForm.value.surName,
orderDescription: this.orderForm.value.orderDescription,
opticianOrders: {
products: this.orderForm.value.products
},
};
console.log(obj);
}
initProduct() {
return this.fb.group({
name: ['', Validators.required],
manufacturerName: ['', Validators.required]
})
}
addProduct() {
const control = <FormArray>this.orderForm.controls['products'];
control.push(this.initProduct());
}
removeProduct(i: number) {
const control = <FormArray>this.orderForm.controls['products'];
control.removeAt(i);
}

Your stackblitz code does not work. You did not import the ReactiveFormsModule and you implemented the forms code in the hello.component.ts also you put the template code in the app.component.html.
See my working sample on stackblitz. It let you add (click on Add) and remove (click on 'x') products from your FormArray.
Form value with two products:
{
name: 'John',
surName: 'Doe',
opticianOrders: {
orderDescription: '1234',
products: [
{ name: 'Cookies', manufacturerName: '' },
{ name: 'More Cookies', manufacturerName: '' }
]
}
}
For typescript this.orderForm.controls.opticianOrders is an AbstractControl which has no controls property. You have to cast it to a FormGroup first. Same with products, you have to cast it to a FormArray.
removeProduct(i: number){
const aFormGroup = this.orderForm.controls.opticianOrders as FormGroup;
const aFormArray = aFormGroup.controls.products as FormArray;
aFormArray.removeAt(i);
}

Try this
orderForm.controls.opticianOrders.controls

Related

error TS7052: Element implicitly has an 'any' type because type 'AbstractControl' has no index signature. Did you mean to call 'get'?

error TS2531: Object is possibly 'null'.
46 <ng-container *ngFor="let userFormGroup of
usersForm.get('users')['controls']; let i=index">
46:48 - error TS7052: Element implicitly has an 'any' type because
type 'AbstractControl' has no index signature. Did you mean to
call 'get'?
46 <ng-container *ngFor="let userFormGroup of
usersForm.get('users')['controls']; let i=index">
TS File
public usersForm!: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() :void {
this.usersForm = this.fb.group({
users: this.fb.array([
this.fb.group({
gHService: [''],
quantity: [''],
startTime: [''],
endTime: [''],
remarks: ['']
})
])
})
}
removeFormControl(i: number) {
let usersArray = this.usersForm.get('users') as FormArray;
usersArray.removeAt(i);
}
addFormControl() {
let usersArray = this.usersForm.get('users') as FormArray;
let arraylen = usersArray.length;
let newUsergroup: FormGroup = this.fb.group({
gHService: [''],
quantity: [''],
startTime: [''],
endTime: [''],
remarks: ['']
})
usersArray.insert(arraylen, newUsergroup);
}
onSubmit(){
console.log(this.usersForm.value);
}
Template File
<form [formGroup]="usersForm" (ngSubmit)="onSubmit()">
<ng-container *ngFor="let userFormGroup of usersForm.get('users')['controls']; let i=index">
<div [formGroup]="userFormGroup">
<label>
Service Name:
<input type="text" formControlName="gHService">
</label>
<label>
Quantity:
<input type="text" formControlName="quantity">
</label>
<label>
Start Time:
<input type="text" formControlName="startTime">
</label>
<label>
End Time:
<input type="text" formControlName="endTime">
</label>
<label>
Remarks:
<input type="text" formControlName="remarks">
</label>
<label>
<button (click)="removeFormControl(i)">remove formGroup</button>
</label>
</div>
</ng-container>
<button type="submit">Submit</button>
</form>
<button (click)="addFormControl()">add new user formGroup</button>
As the error states 'AbstractControl' has no index signature. You need a way to inform typescript that usersForm.get('users') returns a FormArray
In your TS File
get userFormGroups () {
return this.usersForm.get('users') as FormArray
}
In your html
<form [formGroup]="usersForm" (ngSubmit)="onSubmit()">
<div formArrayName='users'>
<ng-container *ngFor="let userFormGroup of userFormGroups.controls; let i=index">
<div [formGroupName]="i">
<!--Other codes here -->
Note the lines
<div formArrayName='users'>
And
<div [formGroupName]="i">

How to add and delete item from array in Angular

I am doing a project that need to display an array and user can add in new data or delete existing data from the array.
I am stuck with how to add and delete item from array.
I tried to use push function to add and pop function to delete but failed.
HTML
<div class="write">
<h1>Student Details</h1>
<div class="data" *ngIf="selectedStudent">
<li> Name: <input type="text" [(ngModel)]="name" placeholder="Please enter Name" value={{selectedStudent.name}}>
</li>
<li> Age:<input type="text" [(ngModel)]="age" placeholder="Please enter Age" class="age"
value={{selectedStudent.age}}></li>
<li>College:<input type="text" [(ngModel)]="college" placeholder="Please enter College"
value={{selectedStudent.college}}></li>
</div>
<p>
<button class="btnA" onclick="addStudent()">Add</button>
<button class="btnE" onclick="editStudent()">Edit</button>
<button class="btnD" onclick="deleteStudent()">Delete</button>
</p>
<li *ngFor="let student of student" [class.selected]="student === selectedStudent" (click)="onSelect(student)">
<span class="badge">{{student.name}} {{student.age}} {{student.college}}</span>
</li>
</div>
.ts
export class WriteComponent implements OnInit {
name: string;
age: number;
college: string;
student = STUDENTS;
selectedStudent: Student;
constructor() {}
ngOnInit(): void {}
onSelect(student: Student): void {
this.selectedStudent = student;
}
}
mock-student.ts (where I store my array)
import { Student } from './student';
export const STUDENTS : Student[]=[
{name:'Johnny',age:24,college:'Harvard'},
{name:'Samantha',age:20,college:'INTI'},
{name:'Aditya',age:21,college:'Sunway'},
{name:'Troy',age:25,college:'TARUC'},
]
Hope this helps.....
Result:
app.component.html
<div class="container">
<h2>Add User</h2>
<form class="form-inline" autocomplete="off" (submit)="addStudent()">
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name" name="name" [(ngModel)]="user.name">
</div>
<div class="form-group">
<label for="pwd">Age:</label>
<input type="number" class="form-control" id="age" name="age" [(ngModel)]="user.age">
</div>
<div class="form-group">
<label for="pwd">College:</label>
<input type="text" class="form-control" id="college" name="college" [(ngModel)]="user.college">
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
<div class="user-list" *ngIf="usersList && usersList.length">
<h2>List of Users</h2>
<table class="table table-condensed">
<thead>
<tr>
<th>SL.No</th>
<th>Name</th>
<th>Age</th>
<th>College</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of usersList; let i = index">
<th>{{i}}</th>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
<td>{{user.college}}</td>
<td>
<button style="margin-right: 5px;" class="btn btn-warning" (click)="editStudent(i)">Edit</button>
<button class="btn btn-danger" (click)="deleteStudent(i)">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
app.component.ts
export class AppComponent implements OnInit{
user: User;
usersList: User[] = []
ngOnInit(): void {
this.resetForm();
}
addStudent() {
this.usersList.push(this.user);
this.resetForm();
}
editStudent(index: number) {
this.user = this.usersList[index];
this.deleteStudent(index);
}
deleteStudent(index: number) {
this.usersList.splice(index, 1);
}
resetForm() {
this.user = {age: null, name: '', college: ''};
}
}
interface User {
name: string;
age: string;
college: string;
}
Deleting an item from the array
You are setting your selectedStudent to one of the instances in your array, so it is simple enough to find its index when you want to remove it from the array.
You can use the splice array function to remove the item at the index.
// declare students here for the purpose of the answer
students: Student[] = [
{name:'Johnny', age:24, college:'Harvard'}
// ... more students here
];
selectedStudent : Student;
onSelect(student:Student): void {
this.selectedStudent = student;
}
deleteStudent(): void {
if (!this.selectedStudent) {
return;
}
// find the index of the selected student
// this works because your selected student is one of the array items
// it wouldn't work if selected student was a copy
const index = this.students.indexOf(this.selectedStudent);
// use splice to remove 1 item starting at the given index
this.students.splice(index, 1);
// todo: logic to reset this.selectedStudent
}
Adding an item to the array
Adding is simple. Use the push array function to append an item to an array.
students: Student[] = [];
name: string;
age: number;
college: string;
addStudent() {
const student = {
name: this.name,
age: this.age,
college: this.college
};
this.students.push(student);
}

How to use one component for validation other two components?

I have three components: GalleryAddComponent to add a new element, GalleryItemComponent, to edit an element, FieldsComponent, the form I want to use in the components: GalleryAddComponent and GalleryItemComponent. All components are inside the GalleryComponent. But when I go to the component GalleryAddComponent to add a new element I get the error: ERROR TypeError: Cannot read property 'controls' of undefined. Also in the component: GalleryItemComponent.
Help solve this problem so that the editing and adding logic works correctly.
template of GalleryAddComponent
<div class="card">
<div class="card-body">
<form [formGroup]="angForm" novalidate>
<app-fields [formGroup]="angForm"></app-fields>
<div class="form-group but-group">
<button (click)="addPost(title.value, url.value); angForm.reset(title.value, url.value)"
[disabled]="angForm.pristine || angForm.invalid"
class="btn btn-primary">Add
</button>
<a routerLink="/" class="btn btn-danger">Back</a>
</div>
</form>
</div>
</div>
code of GalleryAddComponent
export class GalleryAddComponent implements OnInit {
angForm: FormGroup;
isAdded: boolean = false;
constructor(private fb: FormBuilder, private galleryService: GalleryService) {}
ngOnInit() {
this.angForm = this.fb.group({
title: ['', Validators.required],
url: ['', Validators.required]
});
}
addPost(title: string, url: string): void {
this.galleryService.add(title, url).subscribe(res => {
this.isAdded = true;
});
}
}
template of GalleryItemComponent
<div class="card" *ngIf="toggleEdit">
<h4>Edit your post</h4>
<div class="card-body">
<form [formGroup]="angForm" novalidate>
<app-fields [formGroup]="angForm"></app-fields>
<div class="form-group but-group">
<input type="button"
(click)="updatePost(title.value, url.value)"
[disabled]=" angForm.invalid"
class="btn btn-primary" value="Update Post">
</div>
</form>
</div>
</div>
code of GalleryItemComponent
export class GalleryItemComponent implements OnInit {
pic: Picture;
angForm: FormGroup;
constructor(private route: ActivatedRoute,
private galleryService: GalleryService, private fb: FormBuilder) {}
ngOnInit() {
this.angForm = this.fb.group({
title: ['', Validators.required],
url: ['', Validators.required]
});
this.showPost();
}
showPost(): void {
this.route.params.subscribe(params => {
this.galleryService.getPicture(params['id']).subscribe(res => {
this.pic = res;
this.angForm.setValue({title: res.title, url: res.url})
})
})
}
updatePost(title: string, url: string): void {
this.route.params.subscribe(params => {
this.galleryService.update(title, url, params['id']).subscribe(res => {
if (res.id === this.pic.id) {
this.pic.title = title;
this.pic.url = url;
}
});
});
}
}
template of FieldsComponent
<div [formGroup]="formGroup">
<div class="form-group">
<label class="col-md-4">Picture Title</label>
<input type="text" class="form-control" formControlName="title" minlength="1" #title/>
</div>
<div *ngIf="angForm.controls['title'].invalid && (angForm.controls['title'].dirty || angForm.controls['title'].touched)"
class="alert alert-danger">
<div *ngIf="angForm.controls['title'].errors.required">
Title is required.
</div>
</div>
<div class="form-group">
<label class="col-md-4">Picture Address (url)</label>
<input type="url" class="form-control" formControlName="url" #url pattern="https?://.+"
title="Include http://"/>
</div>
<div *ngIf="angForm.controls['url'].invalid && (angForm.controls['url'].dirty || angForm.controls['url'].touched)"
class="alert alert-danger">
Address(url) is required.
<div *ngIf="angForm.controls['url'].errors.required ">
</div>
</div>
</div>
code of FieldsComponent
export class FieldsComponent implements OnInit {
#Input() formGroup: FormGroup;
constructor() {}
ngOnInit() {}
}
You are getting this error because you are referencing angForms.controls in your FieldsComponent which only has one variable: formGroup.
Simply replace angForms in the template HTML code with formGroup and the issue should be resolved.
<div [formGroup]="formGroup">
<div class="form-group">
<label class="col-md-4">Picture Title</label>
<input type="text" class="form-control" formControlName="title" minlength="1" #title />
</div>
<div *ngIf="formGroup.controls['title'].invalid && (formGroup.controls['title'].dirty || formGroup.controls['title'].touched)"
class="alert alert-danger">
<div *ngIf="formGroup.controls['title'].errors.required">
Title is required.
</div>
</div>
<div class="form-group">
<label class="col-md-4">Picture Address (url)</label>
<input type="url" class="form-control" formControlName="url" #url pattern="https?://.+" title="Include http://" />
</div>
<div *ngIf="formGroup.controls['url'].invalid && (formGroup.controls['url'].dirty || formGroup.controls['url'].touched)"
class="alert alert-danger">
Address(url) is required.
<div *ngIf="formGroup.controls['url'].errors.required ">
</div>
</div>
</div>
I think the easy solution here, is to set up the formgroup in the parent component, and pass it on to the child components as input, hence it is given to the child component before the child component html is loaded.
The other solution I would recommend is to use the Resolve Technique offered by Angular, this allows you to load all data before a component is loaded with a quite straight-forward setup.
Here are some references:
https://www.techiediaries.com/angular-router-resolve/
https://alligator.io/angular/route-resolvers/
Cannot read property 'controls' of undefined. This error can come only coz instead of formGroup you have used angForm. Try replacing it as shared by #Wrokar. Also what I understand is you want to show consolidated error messages. So instead of doing it in html for each formcontrol, you should do it in component.ts and make it more generic, by subscribing to value change of each control like below, and show the consolidated error message.
for (const field in this.formGroup.controls) { // 'field' is a string
const control = this.form.get(field); // 'control' is a FormControl
control.valueChanges.subscribe(
(res) => {
// check if it is pristine, dirty, invalid, touched, pattern match if
any
// you can access control.errors
// create the consolidated list and append it in the list of error
messages
}
)
}
Its better to make it generic coz, tomorrow your form can have additional fields and then you dont have to change you FieldsComponent.

angular 5 http.put request returns error "Authentication credentials were not provided"

I want to update user information using the Http put method but it keeps returning
detail: "Authentication credentials were not provided
Here is my editComponent.ts
export class MyProfileEditComponent implements OnInit {
store: any = {};
editProfileForm: FormGroup;
private formSubmitAttempt: boolean;
constructor(fb: FormBuilder, public storeSrv: StoreService) {
this.editProfileForm = fb.group({
'mobile': [''],
'address': [''],
'description': [''],
'storeUserId': [''],
});
}
editProfile() {
this.formSubmitAttempt = true;
if (this.store.mobile || this.store.address || this.store.description) {
this.storeSrv.editStore(this.store.mobile, this.store.address, this.store.description, this.store.storeUserId);
}
}
}
and my storeService.ts code
#Injectable()
export class StoreService {
public updateStoreUrl = this.globals.UPDATE_STORE_URL
store: any = {};
storeId: any;
constructor(private http: Http, private router: Router, private globals: Globals) { }
editStore(mobile: string, address: string, description: string, storeId: any) {
let tempStore = localStorage.getItem('store');
if (tempStore) {
this.store = JSON.parse(tempStore);
this.storeId = this.store.user;
}
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.put(this.updateStoreUrl + this.storeId + '/', {
headers })
.subscribe(res => {
let msg = JSON.parse(res['_body'])['message'];
}, error => {
let msg = JSON.parse(error._body)['message'];
})
};
I wonder where i am getting this wrong as the api endpoint is expecting the storeId in the request...it all looks good in my eyes but then again...Can you help me spot the error or lead me through right path?
update with editComponent.html
<form [formGroup]="editProfileForm" (ngSubmit)="editProfile()" novalidate>
<div class="row">
<div class="col-md-6">
<div class="form-group has-feedback" style="position: relative;">
<label for="storename">Store Name</label>
<input type="text" name="storename" class="form-control" placeholder="{{store.name}}" disabled>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback" style="position: relative;">
<label for="mobilenumber">Mobile Number</label>
<input type="text" name="mobilenumber" class="form-control" placeholder="{{store.mobile}}" [(ngModel)]="store.mobile" [formControl]="editProfileForm.controls['mobile']">
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback" style="position: relative;">
<label for="address">Store Address</label>
<textarea name="address" id="" cols="30" rows="10" class="form-control" placeholder="{{store.address1}}"></textarea>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback" style="position: relative">
<label for="description">Store Description</label>
<textarea name="description" id="" cols="30" rows="10" class="form-control" placeholder="{{store.description}}"></textarea>
</div>
</div>
<input type="text" name="storeUserId" [(ngModel)]="store.userId" [formControl]="editProfileForm.controls['storeUserId']" value="{{store.user}}" hidden>
<div class="btn-container" style="float: right; margin-right: 15px;">
<button class="btn btn-accent btn-flat b-r-10">Edit Profile</button>
</div>
</div>
</form>

Angular 5 not showing user entered values from formarray

In angular 5 I am trying to add new row and remove row functionality. For add new row and delete row I have taken code from here. Everything is working fine but when I am trying to get the user entered value in the new row fields I am not getting those values.
I am getting the value for Event Name. But for other 3 fields like Package Name, Package Price, Max Purchase Limit, I am not getting them.
Here is the code what I have tried.
my event-create.component.html looks like this
<div class="container col-md-12">
<h1 class="page-header">Create Event</h1>
<div class="row show-hide-message">
<div [ngClass]= "messageClass">{{message}}</div>
</div>
<form [formGroup] = "form" (ngSubmit)="onEventSubmit()">
<fieldset>
<div class="form-group">
<label for="eventname">Event Name</label>
<div class='form-group' [ngClass]="{'has-error': form.controls.eventname.errors && form.controls.eventname.dirty,
'has-success': !form.controls.eventname.errors
}">
<input type="text" class="form-control" autocomplete="off" placeholder="Event Name" formControlName="eventname">
<ul class="help-block">
<li *ngIf="(form.controls.eventname.errors?.minlength ) && form.controls.eventname.dirty">Event name should be atleast 5 characters</li>
</ul>
</div>
</div>
<h4>Package Price</h4>
<hr>
<div class="row" formArrayName="sections">
<div class="col-md-12" *ngFor="let section of getSections(form); let i = index">
<div class="form-group col-md-5">
<label for="packagename">Package Name</label>
<input type="text" class="form-control" autocomplete="off" placeholder="Package Name" formControlName="packagename" >
</div>
<div class="form-group col-md-2">
<label for="packageprice">Package Price</label>
<input type="number" class="form-control" autocomplete="off" placeholder="Package Price" formControlName="packageprice" >
</div>
<div class="form-group col-md-2">
<label for="packagelimit">Max Purchase Limit</label>
<input type="number" class="form-control" formControlName="packagelimit" autocomplete="off" >
</div>
<div class="form-group col-md-1">
<br/>
<input type="button" (click)="addPackageRow()" class="btn btn-md btn-success" value="+" name="">
</div>
<div class="form-group col-md-1" *ngIf="getSections(form).length > 1">
<br/>
<input type="button" (click)="removeSection(i)" class="btn btn-md btn-error" value="-" name="">
</div>
</div>
</div>
<input [disabled]=!form.valid type="submit" class="btn btn-primary" value="Submit">
<pre>{{form.value | json}}</pre>
</fieldset>
</form>
</div>
and my event-create.component.ts looks like this
import { Component, OnInit } from '#angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '#angular/forms';
import { FormControlName } from '#angular/forms/src/directives/reactive_directives/form_control_name';
#Component({
selector: 'app-event-create',
templateUrl: './event-create.component.html',
styleUrls: ['./event-create.component.css']
})
export class EventCreateComponent implements OnInit {
form : FormGroup;
packagesArray: FormArray;
constructor(
private formBuilder : FormBuilder,
) { this.createEventForm() }
createEventForm() {
this.form = this.formBuilder.group({
eventname: ['', Validators.compose([
Validators.required,
Validators.minLength(5)
])],
packages: this.packagesArray
})
}
ngOnInit() {
this.form = new FormGroup({
eventname: new FormControl(''),
sections: new FormArray([
this.initSection(),
]),
});
}
initSection() {
return new FormGroup({
packagename: new FormControl(''),
packageprice: new FormControl(''),
packagelimit: new FormControl('')
});
}
initItemRows() {
return this.formBuilder.group({
itemname: ['']
});
}
onEventSubmit() {}
public addPackageRow() {
const control = <FormArray>this.form.get('sections');
control.push(this.initSection());
}
initOptions() {
return new FormGroup({
optionTitle: new FormControl('')
});
}
addSection() {
const control = <FormArray>this.form.get('sections');
control.push(this.initSection());
}
getSections(form) {
return form.controls.sections.controls;
}
public removeSection(i){
const control = <FormArray>this.form.get('sections');
control.removeAt(i);
}
}
Its not showing user entered value in html page also not doing any validation for the eventname field.
Here is the demo what I have done so far
https://stackblitz.com/edit/angular-3s5wwf
Can someone tell me what is going wrong here. Any suggestion or advice will be really appreciable. Thanks.
You need to add this in line 23 and 24
<div class="row" formArrayName="sections">
<div class="col-md-12" *ngFor="let section of getSections(form); let i = index" [formGroupName]="i">
you missed adding the formGroupName for the formArrayName
workinglink

Categories

Resources