单击按钮以使用FormArray类添加URL就是提交整个表单,因此,每次单击按钮时,都不允许用户输入多个URL而不向数据库提交新条目。
在我看来,这似乎是一个事件冒泡的问题,但是使用$ event.stopPropagation根本不会改变行为。
app.component.html
<div class="flex-container">
<form [formGroup]="form" (ngSubmit)="submit()" class="card">
<div class="form-group">
<label for="">Title</label>
<input
type="text"
formControlName="title"
class="form-control"
/>
</div>
<div class="form-group">
<label for="">Image URLs</label>
<input
type="text"
class="form-control"
#url
>
<button (click)="addUrl(url, $event)">Add a URL</button>
<ul>
<li *ngFor="let url of imageUrls.controls" class="form-control" style="color: black;">
{{ url.value }}
</li>
</ul>
</div>
<div class="form-group">
<label for="">Description</label>
<textarea
formControlName="description"
class="form-control"
>
</textarea>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Subscription, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AngularFireDatabase } from '@angular/fire/database';
import { AngularFireList, AngularFireObject } from 'angularfire2/database';
import { AngularFirestore } from '@angular/fire/firestore';
import { FormGroup, FormArray, FormControl, FormBuilder, Validators, AbstractControl } from '@angular/forms';
import { Router } from "@angular/router";
@Component({
selector: 'app-component',
templateUrl: './app-component.component.html',
styleUrls: ['./app-component.component.css']
})
export class GalleryAdminComponent {
form: FormGroup;
constructor(fb: FormBuilder, private router: Router) {
this.form = fb.group({
title: [''],
description: [''],
imageUrls: fb.array([])
});
}
get title() {
return this.form.get('title');
}
get description() {
return this.form.get('description');
}
get imageUrls() {
return this.form.get('imageUrls') as FormArray;
}
addUrl(url: HTMLInputElement, $event) {
$event.stopPropagation(); //doesn't work, clicking the add url button still submits the entire form
(this.imageUrls as FormArray).push(new FormControl(url.value));
url.value = '';
}
addEvent(input: any) {
const itemsRef = this.db.list('events');
itemsRef.push(input);
}
submit() {
console.log("this.form", this.form);
console.log("this.form.value", this.form.value);
this.addEvent(this.form.value);
this.router.navigate(['/gallery']);
}
}
我想使用FormArray,以便可以一次动态添加imageUrls的FormControl对象。然后,这将使用户填写表单,添加零个或多个imageUrl字符串,然后单击“提交”按钮以将form.value对象文字发送到服务器。
答案 0 :(得分:3)
只需添加按钮的
type
属性。
<button type="button" (click)="addUrl(url, $event)">Add a URL</button>
当您点击Add a URL
按钮时,这不会让您的表单提交。
发生这种情况的原因:
按钮的type属性的默认值为“提交”。 Click here to see more。
因此将其设置为type="button"
,以产生不提交表单的按钮。
答案 1 :(得分:-1)
const formArrayName = controle.get('multiExpenseArray')as FormArray;