Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular passing input to child components in ng-content

I want to pass some properties from a parent component to a child component using content projection, is that possible?

For e.g. this is my template:

<my-form [display]="'horiz'">
  Email: <my-input [type]="'email'" ...></my-input>
  Name: <my-input [type]="'name'" [display]="'vert'" ...></my-input>
  ...
</my-form>

Now the my-form component has the template like this:

<form ...>
  <ng-content></ng-content>
</form>

What I want is that the display property of my-form can be accessed by the my-input components, such that it can be overriden by the my-input component as well, like it is for the Name input.

Is that possible?

like image 578
M.Imran Mamda Avatar asked Dec 30 '18 06:12

M.Imran Mamda


People also ask

How do you pass data to a child component?

To let Angular know that a property in a child component or directive can receive its value from its parent component we must use the @Input() decorator in the said child. The @Input() decorator allows data to be input into the child component from a parent component.

How do I pass data from parent to child in Angular 12?

Otherwise, remember the three steps: Prepare Child component to emit data. Bind Property in Parent Component template. Use Property in Parent Component class.


1 Answers

You can use @ContentChildren , made an example on stackblitz:

https://stackblitz.com/edit/angular-content-children-example

I have modified the values in the ngAfterViewInit using the component references from the ContentChildren.

Hope it helps. Feel free to update the code if any better approach is there.

like image 80
Sachin Gupta Avatar answered Oct 23 '22 18:10

Sachin Gupta