简体   繁体   中英

How to change page view dynamically in angular2?

I am learning Angular2 and I get a problem right now. In my page, I have a "Log in" button. After user logged in, I want to change it to "Log out". Since this button is in app.component, it gets loaded only once. Thanks in advance.


My app.component.html

<a *ngIf="signedIn==true" [routerLink]="['Logout']">Log out</a>
<a *ngIf="signedIn==false" [routerLink]="['Login']">Log in</a>

App.component.ts

export class AppComponent {
   constructor(private _loginService: LoginService) {}
   signedIn: boolean = this._loginService.isSignedIn();
}

I think that you should leverage a shared service for this since you're using routing and this involves several components.

If you want to share a state / property between them, you need to add it into your service along with an observable / subject to notify other components when the state changes.

Here is a sample:

export class LoginService {
  isSignedIn: boolean;
  isSignedInSubject: Subject<boolean> = new Subject();

  setSignedIn() {
    this.isSignedIn = true;
    this.isSignedInSubject.next(true);
  }

  setSignedOut() {
    this.isSignedIn = false;
    this.isSignedInSubject.next(false);
  }
}

The main component can subscribe on the subject to be notified when the signedIn state changes.

@Component({
  (...)
  template: `
    <a *ngIf="signedIn==true" [routerLink]="['Logout']">Log out</a>
    <a *ngIf="signedIn==false" [routerLink]="['Login']">Log in</a>      
  `
})
export class AppComponent {
  constructor(private _loginService:LoginService) {
    this._loginService.isSignedInSubject.subscribe(isSignedIn => {
      this.signedIn = isSignedIn;
    });
  }
}

For more details, you could haver a look at this question:

Since RxJS is bundled in with Angular2 the approach I like would be to remodel the isSignedIn member as an Observable and subscribe to it. Example in this plnkr .

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