I want to reload component after a button click from another component Angular 6.
Asked
Active
Viewed 1,689 times
-1
-
add some of your codes which may help us understand your problem better. – Inus Saha Jun 23 '18 at 07:20
-
use eventEmitter(); trigger eventEmitter() in one component and capture that in other component, trigger the refresh function(). :D – Akhil Aravind Jun 23 '18 at 07:23
-
@AkhilAravind can you provide some sample code – Mariyam Mohammed Jalil Jun 23 '18 at 07:51
-
@MariyamMohammedJalil, i will try – Akhil Aravind Jun 23 '18 at 08:34
-
related (not sure if it's a duplicate, since this question is about the navbar) https://stackoverflow.com/questions/47813927/how-to-refresh-a-component-in-angular – Pac0 Jun 24 '18 at 16:58
1 Answers
0
As @MariyamMohammedJalil said you can use an EventEmitter to trigger the update of your first component.
See following sample:
first.component.ts
@Component({
selector: 'first-component',
template: '<div>{{label}}</label>
})
export class FirstComponent {
@Input() update: EventEmitter<string>;
label = 'First Component';
constructor() {}
ngOnInit() {
if (this.update) {
// Subscribe to the event emitter to receive an update event
this.update.subscribe((value: string) => {
this.refresh(value);
})
}
}
refresh(value: string) {
// Do your stuff here
this.label = value;
}
}
second.component.ts
@Component({
selector: 'second-component',
template: '<button (click)="updateFirstCmp()">Update First Component</button>'
})
export class SecondComponent {
@Input() update: EventEmitter<string>;
constructor(){}
updateFirstCmp() {
// Emit an event to update your first component
this.update.emit('Updated First Component');
}
}
And for example you should add following to your app.component.ts
:
updateEventEmitter: EventEmitter<string>;
constructor() {
...
this.updateEventEmitter = new EventEmitter();
}
And in your app.component.html
:
<first-component [update]="updateEventEmitter"></first-component>
<second-component [update]="updateEventEmitter"
Another way do solve your problem can be to enter the first.component
as input parameter to the second.component
to call the refresh function directly without EventEmitter
. See following sample:
app.component.html
<first-component #firstComponent></first-component>
<second-component [firstCmp]="firstComponent"></second-component>
second.component.ts
@Component({
selector: 'second-component',
template: '<button (click)="updateFirstCmp()">Update First Component</button>'
})
export class SecondComponent {
@Input() firstCmp: FirstComponent;
constructor(){}
updateFirstCmp() {
// Update the first component directly
this.firstCmp.refresh('Updated First Component');
}
}
With this sample you don't need to subscribe to an update event, because you're not using an EventEmitter.

Batajus
- 5,831
- 3
- 25
- 38