У меня есть одно требование, где должна быть возможность отправки нескольких форм с помощью одной кнопки с другим компонентом. Возможно ли это реализовать? , Это я предоставил демо-код и Stackblitz в качестве ссылки.
Компонент кнопки отправки
HTML
<div class="form-group">
<button class="btn btn-primary" (click)="submitBtn()">Save</button>
</div>
Component.ts
@Output() submitBtnClickEvt: EventEmitter<any> = new EventEmitter<any>();
constructor() { }
ngOnInit() {
}
submitBtn() {
console.log('Submit clicked');
this.submitBtnClickEvt.emit({details: { clicked: true}});
}
Компонент формы
Один
HTML
<div class="formContainer">
<h5>One</h5>
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
<input type = "text" name = "fullName" placeholder = "Your full name" formControlName="fullName" >
<br/>
<input type = "email" name = "email" placeholder = "Your email" formControlName="email" >
<br/>
<textarea name = "message" placeholder = "Your message" formControlName="message" ></textarea>
</form>
</div>
Компонент
createContactForm(){
this.contactForm = this.formBuilder.group({
fullName: [''],
email: [''],
message: ['']
});
}
onSubmit() {
console.log('Your form data : ', this.contactForm.value );
}
Два
HTML
<div class="formContainer">
<h5>Two</h5>
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
<input type = "text" name = "fullName" placeholder = "Your full name" formControlName="fullName" >
<br/>
<input type = "email" name = "email" placeholder = "Your email" formControlName="email" >
<br/>
<input type = "password" name = "password" placeholder = "Your password" formControlName="password" >
</form>
</div>
Компонент
createContactForm(){
this.contactForm = this.formBuilder.group({
fullName: [''],
email: [''],
password: ['']
});
}
onSubmit() {
console.log('Your form data : ', this.contactForm.value );
}
Редактировать
Отправить компонент
constructor(
private submitService: SubmitService
) {}
ngOnInit() {
combineLatest([
this.submitService.setFormConfDetailValue$.asObservable()
])
.pipe(
tap(([ formTwo]) => {
if (formTwo) {
console.log('Form data: ', formTwo);
}
})
).subscribe();
}
submitBtn() {
console.log('Submit clicked');
this.submitService.submitForms$.next();
}
Отправить услугу
import { EventEmitter, Injectable } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
@Injectable()
export class SubmitService {
public submitForms$: Subject<any> = new Subject();
public setFormConfDetailValue$: BehaviorSubject<any> = new BehaviorSubject(null);
constructor() {console.log("test from service") }
}