I have some component with checkboxes. And I have another component with table. The components are not one inside another. When I uncheck checkbox I need to change classes to some table columns on table component. What is the best way to do it ?
-
dzone.com/articles/… and stackoverflow.com/a/36076701/6478359Muhammet Can TONBUL– Muhammet Can TONBUL2020-03-30 14:03:22 +00:00Commented Mar 30, 2020 at 14:03
-
Is there a common parent component template where both the children components are used?Barremian– Barremian2020-03-30 14:04:47 +00:00Commented Mar 30, 2020 at 14:04
-
@MichaelD, the standard root app.componentMikael– Mikael2020-03-30 14:05:52 +00:00Commented Mar 30, 2020 at 14:05
-
@MuhammetCanTONBUL, what is the good way if it is not paren->child structure in my case ?Mikael– Mikael2020-03-30 14:20:13 +00:00Commented Mar 30, 2020 at 14:20
2 Answers
In angular most of the communication happens in the following ways.
- PARENT -> CHILD , use Input EventEmitter.
- CHILD -> PARENT, use Output EventEmitter.
- If no immediate relation between components -> Use a Data Service, angular service which both the components are dependent on to publish and retrieve data.
- Also you can use the ViewChild, if your child component is housed inside the parent component.
Comments
From your comment, both the components are used in app.component.html. Then you can create an event emitter for the change event in the check-box component. And in the app.component.html, assign a template variable to table component and assign any of it's function directly as callback for checkbox component's emitted event. Try the following
checkbox.component.html
<input type="checkbox" id="1" (change)="change.emit($event)"> Checkbox
checkbox.component.ts
@Output change = new EventEmitter();
app.component.html
<app-checkbox (change)="table1.checkboxChange($event)"></app-checkbox>
<app-table #table1></app-table>
table.component.ts
checkboxChange(event: any) {
// change CSS selector of element
}
One advantage of this method is the parent component remains untouched and so an additional rerouting is avoided.