简体   繁体   中英

Reload angular component with button click

I working on a angular 8 application. In that application I want to reload a component, when a button clicked which is inside of another component. I found a way to do that with router, first navigate to sample component and then navigate to actual component as shown in below code.

this.router.navigateByUrl('/SampleComponent', { skipLocationChange: true });
this.router.navigate(["yourLandingComponent"]);

But in this application I don't have used router. This is simple, single page application. I have used ngIf to render components as shown in below.

<div class="row main-wrapper">
    <app-section-rental class="container-fluid p-0" *ngIf="tabset.tab0"></app-section-rental>
    <app-section-insuarance class="container-fluid p-0" *ngIf="tabset.tab1"></app-section-insuarance>
    <app-section-additionals class="container-fluid p-0" *ngIf="tabset.tab2"></app-section-additionals>
    <app-section-optionals class="container-fluid p-0" *ngIf="tabset.tab3"></app-section-optionals>
    <app-price-breakdown class="container-fluid p-0" *ngIf="tabset.tab4"></app-price-breakdown>
</div>

So I want to know how to reload my component with a button click, which is inside of another component.

I also found another way to do this with angular subscription. But the problem is I that subscription get an element, I don't have to change any state which make any change in HTML. So I don't know whether my component get reloaded or not. Is it compulsory to do any change in DOM element, in order to reload a component?

You could use Obersavables from rxjs . This Observable contains the data displayed/updated in you component.

private _testSubject = new BehaviorSubject<string>('old data');
testObservable$: Observable<string> = this._testSubject.asObservable();

The following function will update your data:

public refresh(){
   this._testSubject.next('new Data');
}

Call this function on you refresh-button's onClick . And finally you can use your Observable in your components html like that:

<div>
   {{(testObservable$|async)}}
</div>

Hope that helps!

EDIT:

As I noticed in your comments, your refresh button is in an parent component. In this case you could implement your observable in your parent component and work with an input in your comopnent:

  @Input()
  yourObservable: Observable<string>;

and in your parent component:

<app-your-compomemt [yourObservable]="testObservable$"></app-your-compomemt>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM