Home > Back-end >  How do I change the button name depending on the route name without clicking it?
How do I change the button name depending on the route name without clicking it?

Time:06-07

I want to change the name of the button on my header. If I go to login it will change the name of the button to "Signup" and if I go to signup it will change the button name to "Login". I want to change the button name without clicking it. My problem is when I use this.router.navigate(['login']) in another component the button name is not changed to "signup". How can I do this? Here's my code:

header.component.ts

changedText() {
    if(this.router.url.includes('/signup')) {
      this.text = 'Login';
    } else {
      this.text = 'Signup';
    }
  }

header.component.html

<button *ngIf="!IsLoggedIn()" mat-raised-button color="warn"  (change)="changedText()" (click)="toggleButton()">{{text}}</button>

CodePudding user response:

export class AppComponent implements OnInit {

  public text: string

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.url.subscribe((url) => {
      this.text = url[0].path == 'signup' ?  'Signup' : 'Login'
    });
  }
  
}

CodePudding user response:

TS:

  readonly label$ = this.router.events
    .pipe(
      filter(event => event instanceof NavigationEnd),
      map(event => event.url.includes('/signup') ? 'Login' : 'Signup')
    );

  constructor(private readonly router: Router) {
  }

HTML:

  <button *ngIf="!IsLoggedIn()" 
          mat-raised-button 
          color="warn" 
           
          (click)="toggleButton()">{{label$ | async}}</button>
  • Related