Reputation: 4756
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?
thanks
Upvotes: 0
Views: 4955
Reputation: 2065
you can use services, as follow:
form.service.ts file
@Injectable()
export class FormService {
onFormSubmitted = new EventEmitter<any>();
}
then register this service in the appModule providers appModue.ts file
providers: [
...
FormService
...
]
firstComponent.ts file
@Component({
...
});
export class FirstComponent implements{
constructor( public formService:FormService) {}
onFormSubmit(formData:any) {
this.formService.onFormSubmitted.emit(formData);
}
}
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
}
}
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.
Upvotes: 3