简体   繁体   English

如何选择要在ngIf中调用的函数?

[英]How to choose function to call in ngIf?

I want to call, depending on the value of the variable, this.loggedInService.isLoggedIn methods: login() and logout() 我想根据变量的值调用this.loggedInService.isLoggedIn方法: login()logout()

  • If the value of the variable !this.loggedInService.isLoggedIn then call login() 如果变量!this.loggedInService.isLoggedIn的值,则调用login()
  • If !this.loggedInService.isLoggedIn then this method logout() . 如果!this.loggedInService.isLoggedIn则此方法为logout()

How to implement it correctly in app.html ? 如何在app.html中正确实现它?

template: 模板:

 <li class="nav-item">
    <a class="btn btn-outline-success" 
      [class.btn-outline-success]="!this.loggedInService.isLoggedIn"
      [class.btn-outline-danger]="this.loggedInService.isLoggedIn" 
      ngIf ....>
      {{this.loggedInService.isLoggedIn ? 'Exit' : 'Enter'}}
    </a>
  </li>

app.ts: 应用程式:

export class AppComponent implements OnInit {
  constructor(public loggedInService: LoggedinService, public router: Router) {}

  ngOnInit() {}

  login(): void {
    this.loggedInService.login().subscribe(() => {
      if (this.loggedInService.isLoggedIn) {
        let redirect = this.loggedInService.redirectUrl
          ? this.loggedInService.redirectUrl
          : '/gallery';
        this.router.navigate([redirect]);
      }
    });
  }

  logout(): void {
    this.loggedInService.logout();
  }
}

You can use ternary operator to run a function based on state like this 您可以使用三元运算符基于这样的状态运行函数

<li (click)="this.loggedInService.isLoggedIn ? logout() : logIn()" >
{{this.loggedInService.isLoggedIn ? logout : logIn}}
</li>

Let this logic move ts file and Just create one function toggleLogin() in ts file and call it from the html. 让此逻辑移动ts文件,然后在ts文件中创建一个功能toggleLogin()并从html调用它。

In HTML 在HTML中

  <li class="nav-item">
                <a class="btn btn-outline-success"
                   [class.btn-outline-success]="!this.loggedInService.isLoggedIn"
                   [class.btn-outline-danger]="this.loggedInService.isLoggedIn"
                   (click)="toggleLogin()"
                  >
                    {{this.loggedInService.isLoggedIn ? 'Exit' : 'Enter'}}
                </a>
            </li>

in ts file 在ts文件中

 toggleLogin(): void {
        if(this.loggedInService.isLoggedIn){
            this.logout();
       }else{
            this.login();
       }
    }

调用将检查this.loggedInService.isLoggedInlogInOrOut函数,然后调用适当的函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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