在其他组件上提交表单 [英] Submitting a form on a different component
问题描述
我已经在一个组件上创建了一个基于模型的表单,但是提交"按钮位于另一个组件上.
I have created a model based form on a component, however the submit button is placed on a different component.
现在,当您按下按钮时,将触发此功能:
right now when you press the button this function is triggerd:
@Input()
form: any;
...
if(this.form.valid)
this.saveDefinition();
但是,如果表单无效,我想使用该表单将信号发送"回我的组件.如果表单无效,则应突出显示所有无效字段(就像在同一组件上提交表单时一样).
however I want to "send a signal" back to my component with the form if the form is invalid. If the form is invalid it should highlight all the invalid fields (Like it would when you would submit the form on the same component).
我搜索了一段时间,我什至不知道这是否可行,如果可以的话,你们可以帮我上路吗?
I've searched for a while and I can't even find out if this is possible, if it is possible can you guys help me get on my way?
谢谢
推荐答案
您可以使用以下服务:
form.service.ts文件
form.service.ts file
@Injectable()
export class FormService {
onFormSubmitted = new EventEmitter<any>();
}
然后在appModule提供程序appModue.ts文件中注册此服务
then register this service in the appModule providers appModue.ts file
providers: [
...
FormService
...
]
firstComponent.ts文件
firstComponent.ts file
@Component({
...
});
export class FirstComponent implements{
constructor( public formService:FormService) {}
onFormSubmit(formData:any) {
this.formService.onFormSubmitted.emit(formData);
}
}
secondComponent.ts文件
secondComponent.ts file
export class SecondComponent implements OnInit{
constructor ( public formService:FormService ) {}
ngOnInit() {
this.formService.onFormSubmitted.subscribe( (formData : any ) => {
this.onFormSubmit(formData);
})
}
onFormSubmit(formData : any) {
// your logic for submitting the form
}
}
第一个和第二个组件具有相同的FormService实例,因此它们具有相同的eventEmitter实例,第一个组件在表单提交时发出事件,而第二个组件在侦听该事件. 它称为使用服务的跨组件通信.
the first and the second component have the same instance of FormService, so they have the same instance of the eventEmitter, the first component emitting the event when the form is submitting and the second component is listening to it. its called cross-component communication using services.
这篇关于在其他组件上提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!