Unique Solution #ABC
One effective approach is to introduce a boolean property in the parent component, such as submitted = false
, which can be manually set to true
upon form submission by the user. This property can then be passed down through multiple layers of components using @Input()
bindings until it reaches the general input component. In this component, the property can be used in conjunction with ngIf
to display any errors.
Innovative Solution #XYZ
After closely examining Material Angular inputs and their custom validation matchers, I delved into the source code and discovered that the base classes, NgForm
and FormGroupDirective
, are injected into constructors. Through dependency injection, it became apparent that one could access the submitted
property by obtaining the FormGroupDirective/NgForm instances. By utilizing dependency injection, the submitted
property can be exclusively housed within the general input component. Here's an example snippet showcasing how this can be achieved:
constructor(
@Optional() private form: NgForm,
@Optional() private group: FormGroupDirective,
) { }
ngOnInit() {
this.group.ngSubmit.subscribe(e => {
this.submittd = this.group.submitted || this.form.submitted;
});
}
To visualize this concept in action, a demonstration has been created. Upon accessing the provided StackBlitz link, you can observe firsthand how the property tracking functions.
Initiate the process by checking the initial state of the FormGroupDirective in the console. Subsequently, trigger the ngSubmit event by clicking the submit button. The Funny button displays the updated submitted
status present on the FormGroupDirective instance.
An additional example incorporates error messaging alongside color indicators for input fields. Feel free to explore this functionality in action by visiting the following StackBlitz link. Simply delete the input value and click "Submit" to witness the dynamics in play.