charsi
charsi

Reputation: 3847

Change variable in subcomponent angular 2+

I am trying to add a class to an element in a child component when a button is clicked in the parent component.

For this I have a button in the parent component to change a variable --

<button type="button" (click)="showModal=true">clicky</button>

and in the child a modal with a directive? to add class when the variable is true.

<div class="modal" [ngClass]="{'show': showModal}" 
     id="exampleModal" tabindex="-1" role="dialog">

If I move the html for the modal to the parent component everything works. What is the easiest way of passing the variable to the child component?

Upvotes: 0

Views: 915

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68655

To pass data into the child components you can use @Input decorator in the child component. This will let parent components to pass data into the child components using binding. This can be in the template of the parent component.

<child-cmp [myParam]='data'></child-cmp>

And child component

@Component({
   selector: 'child-cmp',
   ...
})
export class ChildCmp {
   @Input() myParam: any
}

Upvotes: 2

Related Questions