0

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?

1

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

8 Comments

I am passing the variable as <child-cmp [showModal]='showModal'></child-cmp> but this only works once. After I close the modal by setting the variable back to false the button from the parent no longer works.
If you are expecting the parent to change the value of that property, you need to watch for changes to that property. You can do that with a setter or with the ngOnChanges lifecycle hook.
Let me know if you need sample code of watching for changes to the property @charsi
@DeborahK I've tried using a setter. I get the value from the parent when it changes from false to true. However when I change it back to false in the child the value in the parent still remains true and hence it does not get sent again. So I am guessing what I need is a two way data binding between the child and parent.
@DeborahK Any way to push the true value to the child again? even when the value stays true in the parent
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.