I have a child component with an <input> element. I can customize the component from a parent using several attributes like placeholder, maxlength, required, etc. But I cannot get type= to fallthrough like the rest.
I’ve searched for hours but I can’t find anything that specifies that ‘type=’ is handled differently…
For example:
Parent component:
<code><template><child-component type=text maxlength=20 /></template></code><code><template> <child-component type=text maxlength=20 /> </template> </code><template> <child-component type=text maxlength=20 /> </template>
Child component
<code><template><input :type="[$attrs.type]" :maxlength="[$attrs.maxlength]" /></template></code><code><template> <input :type="[$attrs.type]" :maxlength="[$attrs.maxlength]" /> </template> </code><template> <input :type="[$attrs.type]" :maxlength="[$attrs.maxlength]" /> </template>
‘maxlength’ and other attributes fall through as expected, including parent’s class and style attributes merging with the child’s class and style attributes.
I did some experimenting and found that if the type attribute is not specified in the parent, a type attribute with no value shows up in the child element only if I use the square brackets around the attrs object specification, like :type=”[$attrs.type]”.
If the type attribute is not specified in the parent, a type attribute does not show up in the child element if there are no square brackets around the attrs object specification, like :type=”$attrs.type”.
It looks like the no square brackets format is the way to go.
Hope this helps others as I had to do a lot of trial and error testing to come to these observations. If anybody can add to this discussion, please comment.
3
-
I don’t think its a good idea to have a common Input component for all types. It will clutter your logic. Having separate input component for each field is a much better way.
-
Answering your problem, you could do
<child-component input-type="text"/>
In your Child Component
<input :type="inputType"/>