-1

I want to reload component after a button click from another component Angular 6.

georgeawg
  • 48,608
  • 13
  • 72
  • 95

1 Answers1

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