Ronen
Ronen

Reputation: 837

Angular - Accessing Host properties from a child component

I created a set of custom form components that renders the label, input and validations.

The component has a layout attribute that allow setting the position of the HTML elements (the component has defaults).

In most cases the layout for all components on a specific form is the same. I would like to be able to set the layout on the host component so the component will try taking it from the host component.

So instead of repeating layout like:

<div class='input-group'>
    <my-input type="text" id="name" label="Name" [layout] ="{'col_label':2, 'col_input':3,'col_validation':2}"></my-input>
    <my-input type="text" id="address" label="address" [layout] ="{'col_label':2, 'col_input':3,'col_validation':2}"></my-input>
    <my-input type="number" id="zip" label="zip" [layout] ="{'col_label':2, 'col_input':3,'col_validation':2}"></my-input>
</div>

I will have properties on my Form’s component

export class UserFormComponent {
    col_label=2;
    col_input=3;
    col_validation'=2;
.
.
.
}

And on the component I can query the host for the values (if exists). something like:

.
.
this._gridLabelColumn = parent.col_label;
this._gridInputColumn = parent.col_input;
.
.

This will make the html much shorter:

<div class='input-group'>
    <my-input type="text" id="name" label="Name"></my-input>
    <my-input type="text" id="address" label="address"></my-input>
    <my-input type="number" id="zip" label="zip"></my-input>
</div>

Please note that components can be hosted in many forms/components, so I really don't know what is the host type.

Upvotes: 1

Views: 343

Answers (1)

matejko219
matejko219

Reputation: 1761

I suggest you to communicate between parent and children using service or @ViewChild. It is all described in guide urls that I pasted.

EDIT: Check this answer but it depends on parent component type.

Other option is to use @Input and pass parent instance into each my-input.

Upvotes: 1

Related Questions