I’m trying to show a clarifying "Required" placeholder text for all input fields that have "required" attribute set to true.
So basically the same as
<mat-form-field>
<input formControlName="fieldName" matInput required="true" placeholder="Required">
</mat-form-field>
But programmatically for all required fields. Form fields "required" status is set at the component initialization based on various conditions.
If there is a way to do this for all components / pages of the angular app, not just for one component that would be even better!
2
Answers
Looks like you need a directive that will do it for you, we can create a directive
addPlaceholder
which will first get theformControlName
usinggetAttribute
and then through thecontrolContainer.control
get the parent form, then finally we get access to theFormControl
of the element, check if hasrequired
validator and then finally set the placeholderPlease find below working example!
directive
main.ts
stackblitz
To apply a directive to several elements we use the selector
In this case the selector is a tag "input" with an attribute "formControl" or attribute "formControlName"