- 首页
- 其他开发
- Angular 5 FormArray 从数据库中获取数据并显示行
Angular 5 FormArray 从数据库中获取数据并显示行
[英] Angular 5 FormArray get data from database and show rows
本文介绍了Angular 5 FormArray 从数据库中获取数据并显示行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是 angular 的新手.我创建了一个事件组件,用户在其中输入带有包的事件名称.当用户创建一个事件时,它具有通过添加和删除行创建多个包的功能.为此,我使用了 FormArray
.
这里一切正常.但是,当我尝试在事件编辑组件中获取这些值时,我正在获取事件名称的值,但是当我尝试获取包详细信息时,我在显示带有填充值的行时有点困惑.
这是我到目前为止所做的代码
event-edit.component .ts 看起来像这样
import { Component, OnInit } from '@angular/core';import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';从'@angular/forms/src/directives/reactive_directives/form_control_name'导入{FormControlName};从@angular/router"导入 { ActivatedRoute, Router };从'@angular/common/http' 导入 { HttpClient };从 '../event.service' 导入 { EventService };@成分({选择器:应用程序事件编辑",templateUrl: './event-edit.component.html',styleUrls: ['./event-edit.component.css']})导出类 EventEditComponent 实现 OnInit {事件 = {};构造函数(私有 http: HttpClient,专用路由器:路由器,私人路线:ActivatedRoute,私有 formBuilder :FormBuilder,私人事件服务:事件服务,) { this.createEventForm();}createEventForm() {this.form = this.formBuilder.group({事件名称: ['', Validators.compose([Validators.required,Validators.minLength(5)])],})}ngOnInit() {this.getOneEvent(this.route.snapshot.params['id']);this.form = new FormGroup({eventname: new FormControl('', [ Validators.required, Validators.minLength(5)]),部分:新 FormArray([this.initSection(),]),});}getOneEvent(id) {this.http.get(this.domain + '/api/event/' + id).subscribe(data => {this.event = data['eventname'];this.packages = data['packages'];//获取包作为数组对象});}公共 addPackageRow() {const control = <FormArray>this.form.get('sections');control.push(this.initSection());}addSection() {const control = <FormArray>this.form.get('sections');control.push(this.initSection());}initSection() {返回新的表单组({包名:new FormControl('', [ Validators.required, Validators.minLength(5)]),包装价格:新的 FormControl(''),packagelimit: new FormControl('')});}getSections(形式){返回 form.controls.sections.controls;}公共删除部分(i){const control = <FormArray>this.form.get('sections');control.removeAt(i);}}
event-edit.component.html 看起来像这样
<h1 class="page-header">事件编辑</h1><!-- <div class="row show-hide-message"><div [ngClass]= "messageClass">{{message}}</div>
--><form [formGroup] = "form" (ngSubmit)="updateEvent(event._id)"><字段集><div class="form-group"><label for="eventname">事件名称</label>
<input type="text" formControlName="eventname" class="form-control" autocomplete="off" [(ngModel)]="eventname" placeholder="Event Name" >
<h4>套餐价格</h4><小时><div class="row" formArrayName="sections"><div class="col-md-12" *ngFor="let section of getSections(form); let i = index" [formGroupName]="i"><div class="form-group col-md-5"><label for="packagename">包名称</label><input type="text" class="form-control" autocomplete="off" placeholder="Package Name" formControlName="packagename">
<div class="form-group col-md-2"><label for="packageprice">包裹价格</label><input type="number" class="form-control" autocomplete="off" placeholder="Package Price" formControlName="packageprice" >
<div class="form-group col-md-3"><label for="packagelimit">最大购买限额</label><input type="number" class="form-control" formControlName="packagelimit" autocomplete="off" >
<div class="form-group col-md-1"><br/><input type="button" (click)="addPackageRow()" class="btn btn-md btn-success" value="+" name="">
<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="">
<input type="submit" class="btn btn-primary" value="更新"></fieldset></表单>
解决方案
您只需遍历包中的数据并将其添加到表单中即可.
服务结束后,您将初始化循环:-
getOneEvent(id) {this.http.get(this.domain + '/api/event/' + id).subscribe(data => {this.event = data['eventname'];this.packages = data['packages'];//获取包作为数组对象for(let package of this.packages){this.addSection(包)}});}
然后在您的部分功能中,您将相同的内容传递给 initSection.
addSection(package) {const control = <FormArray>this.form.get('sections');control.push(this.initSection(package));}
然后最后在你的 initSection 你将赋值
initSection(package) {如果(!包){var 包 = {包裹名字 : "",包装价格:"",包限制:"}}返回新的表单组({packagename: new FormControl(package.packagename, [Validators.required, Validators.minLength(5)]),包价格:新的 FormControl(package.packageprice),packagelimit: 新的 FormControl(package.packagelimit)});}
if 条件用于添加空白(新)项.
同时从 ngOnInit 中删除 addSection 的调用,否则第一行将留空.
I am just a newbie to angular. I have create a event component where user enters the event name with packages. When user creates an event it has the functionality for creating multiple packages with add and remove row. For that I have used FormArray
.
Everything is fine here. But when I am trying to get those values in event edit component I am getting the value of event name but when I am trying to get the packages details I am little bit confused in showing rows with filled values.
Here is the code what I have done so far
event-edit.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';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { EventService } from '../event.service';
@Component({
selector: 'app-event-edit',
templateUrl: './event-edit.component.html',
styleUrls: ['./event-edit.component.css']
})
export class EventEditComponent implements OnInit {
event = {};
constructor(
private http: HttpClient,
private router: Router,
private route: ActivatedRoute,
private formBuilder : FormBuilder,
private eventService : EventService,
) { this.createEventForm(); }
createEventForm() {
this.form = this.formBuilder.group({
eventname: ['', Validators.compose([
Validators.required,
Validators.minLength(5)
])],
})
}
ngOnInit() {
this.getOneEvent(this.route.snapshot.params['id']);
this.form = new FormGroup({
eventname: new FormControl('', [ Validators.required, Validators.minLength(5)]),
sections: new FormArray([
this.initSection(),
]),
});
}
getOneEvent(id) {
this.http.get( this.domain + '/api/event/' + id).subscribe(data => {
this.event = data['eventname'];
this.packages = data['packages']; //getting packages as array object
});
}
public addPackageRow() {
const control = <FormArray>this.form.get('sections');
control.push(this.initSection());
}
addSection() {
const control = <FormArray>this.form.get('sections');
control.push(this.initSection());
}
initSection() {
return new FormGroup({
packagename: new FormControl('', [ Validators.required, Validators.minLength(5)]),
packageprice: new FormControl(''),
packagelimit: new FormControl('')
});
}
getSections(form) {
return form.controls.sections.controls;
}
public removeSection(i){
const control = <FormArray>this.form.get('sections');
control.removeAt(i);
}
}
event-edit.component.html looks like this
<div class="container col-md-10">
<h1 class="page-header">Event Edit</h1>
<!-- <div class="row show-hide-message">
<div [ngClass]= "messageClass">{{message}}</div>
</div> -->
<form [formGroup] = "form" (ngSubmit)="updateEvent(event._id)">
<fieldset>
<div class="form-group">
<label for="eventname">Event Name</label>
<div class='form-group'>
<input type="text" formControlName="eventname" class="form-control" autocomplete="off" [(ngModel)]="eventname" placeholder="Event Name" >
</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" [formGroupName]="i">
<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-3">
<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 type="submit" class="btn btn-primary" value="Update">
</fieldset>
</form>
</div>
解决方案
You will have to just loop through data in packages and add it to form.
After your service you will intialize the loop :-
getOneEvent(id) {
this.http.get( this.domain + '/api/event/' + id).subscribe(data => {
this.event = data['eventname'];
this.packages = data['packages']; //getting packages as array object
for(let package of this.packages){
this.addSection(package)
}
});
}
then in your sections function you will pass the same to initSection.
addSection(package) {
const control = <FormArray>this.form.get('sections');
control.push(this.initSection(package));
}
then finally in your initSection You will assign values
initSection(package) {
if (!package) {
var package = {
packagename : "",
packageprice : "",
packagelimit : ""
}
}
return new FormGroup({
packagename: new FormControl(package.packagename, [Validators.required, Validators.minLength(5)]),
packageprice: new FormControl(package.packageprice),
packagelimit: new FormControl(package.packagelimit)
});
}
The if condition is for when you add a blank (a new ) item.
Also remove the call of addSection from ngOnInit else first row will be left empty.
这篇关于Angular 5 FormArray 从数据库中获取数据并显示行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文