简体   繁体   English

根据 ngIf 条件更改 Angular 中 NavBar 的内容

[英]Change content of NavBar in Angular based on ngIf condition

I am a beginner in Angular and Node JS.我是 Angular 和 Node JS 的初学者。 I am trying a simple navigation bar change based on ngIf condition.我正在尝试基于 ngIf 条件进行简单的导航栏更改。 However, it doesn't seem to work.但是,它似乎不起作用。

I have already tried it using static member variables.我已经尝试过使用静态成员变量。

Also, tried creating a method which changes the value of isUserAuthenticated in navbar.component and called the methods in homepage.component as well as dashboard.component .此外,尝试创建一个方法来更改isUserAuthenticatednavbar.component的值,并调用homepage.componentdashboard.component

I have also done console.log() and checked the value of isUserAuthenticated variable.我也做了console.log()并检查了isUserAuthenticated变量的值。 It is being updated on both the homepage.component as well as dashboard.component .它正在homepage.componentdashboard.component上更新。 However, the NavBar always remains the same.但是,NavBar 始终保持不变。

I have changed the value directly in navbar.component and then it works.我直接在 navbar.component 中更改了值,然后它就可以工作了。 So, I am wandering why it is not working if I change the value from other components.所以,我想知道为什么如果我更改其他组件的值它不起作用。

navbar.component.html导航栏.component.html

       <div *ngIf="!isUserAuthenticated">
          <li class="nav-item">
            <a class="nav-link" href="/"> EX FALSE </a>
          </li>
        </div>

        <div *ngIf="isUserAuthenticated">
          <li class="nav-item">
            <a class="nav-link" href="/"> EX TRUE </a>
          </li>
        </div>

navbar.component.ts导航栏.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  isUserAuthenticated = true;

  constructor() { }

  ngOnInit() { }

  public authenticate() {
    this.isUserAuthenticated = false;
    return  this.isUserAuthenticated;
  }
  public deauthenticate() {
    this.isUserAuthenticated = true;
    return  this.isUserAuthenticated;
  }
}

homepage.component.ts主页.component.ts

import { Component, OnInit } from '@angular/core';
import { NavbarComponent } from '../navbar/navbar.component';


@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

  constructor( ) {

  }

  ngOnInit() {

    console.log("here");
    this.deauthenticate();


  }

  public deauthenticate()
  {
    const comp2 = new NavbarComponent();
    comp2.deauthenticate();
    console.log(comp2.deauthenticate());
  }
}

dashboard.component.ts仪表板.component.ts

import { Component, OnInit } from '@angular/core';
import { NavbarComponent } from '../navbar/navbar.component';



@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  constructor( ) {
  }

  ngOnInit() {

    this.authenticate();
  }

  public authenticate()
  {
    const comp2 = new NavbarComponent();
    comp2.authenticate();
    console.log(comp2.authenticate());
  }

}

I want that dashboard component shows "EX TRUE" in NavBar and homepage component shows "EX FALSE" in NavBar.我希望dashboard组件在导航栏中显示“EX TRUE”, homepage组件在导航栏中显示“EX FALSE”。

As mentioned in comment you need to create service for authentication check this for full example如评论中所述,您需要创建用于身份验证的服务, 请查看完整示例

@Injectable()
export class AuthenticationService {
  authenticated$: BehaviorSubject<boolean> = new BehaviorSubject(false);

  public authenticate() {
    this.authenticated$.next(true);
  }

  public deauthenticate() {
    this.authenticated$.next(false);
  }
}

you inject it this way to be able to use it in template你以这种方式注入它以便能够在模板中使用它

import { Component } from '@angular/core';

import { AuthenticationService } from '../authentication/authentication.service';

@Component({
  selector: 'my-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: [ './navbar.component.css' ]
})
export class NavbarComponent {
  constructor(
    public authenticationService: AuthenticationService,
  ) {
  }
}

and then in template you can do this然后在模板中你可以这样做

Authenticated {{ authenticationService.authenticated$ | async }}

<div *ngIf="(authenticationService.authenticated$ | async) === true">
  <li class="nav-item">
    <a class="nav-link" href="/">EX TRUE</a>
  </li>
</div>

<div *ngIf="(authenticationService.authenticated$ | async) === false">
  <li class="nav-item">
    <a class="nav-link" href="/">EX FALSE</a>
  </li>
</div>

<button (click)="authenticationService.authenticate()">Authenticate</button>
<button (click)="authenticationService.deauthenticate()">Deauthenticate</button>

Although i would suggest using ngSwitch in this case like this:虽然我建议在这种情况下使用 ngSwitch,如下所示:

<div>
  <li class="nav-item" [ngSwitch]="authenticationService.authenticated$ | async">
    <a class="nav-link" href="/" *ngSwitchCase="true">EX TRUE</a>
    <a class="nav-link" href="/" *ngSwitchDefault>EX FALSE</a>
  </li>
</div>

Also if you want separate state for some parts of your site you can do it like this:此外,如果您希望网站的某些部分具有单独的状态,您可以这样做:

@Component({
  selector: 'my-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: [ './homepage.component.css' ],
  // this way you have a separate instance of AuthenticationService here anything that will use this service and is rendered under this component will use a localized version of this service
  providers: [AuthenticationService],
})
export class HomepageComponent {
  constructor(
    public authenticationService: AuthenticationService,
  ) {
  }
}

That is not how things are designed to work.事情不是这样设计的。 For this scenario, you need to create a Service such as AuthService which will be shared across both component.对于这种情况,您需要创建一个Service例如AuthService ,它将在两个组件之间共享。

AuthEventSvc身份验证事件服务

export class AuthEventSvc{

   private authEvent = new BehaviorSubject<boolean>(true);
   constructor(){}

   emitAuthStatus(state: boolean){
     this.authEvent.next(state);
   }

   authListener(){
     return this.authEvent.asObservable();
   }

}

and then emit from HomeComponent然后从HomeComponent发出

export class HomepageComponent implements OnInit {

  constructor(private authEvent: AuthEventSvc ) {

  }

  ngOnInit() {
    this.authEvent.emitAuthStatus(false);
  }
}

and subscribe it in NavBarComponent并在NavBarComponent 中订阅它

export class NavbarComponent implements OnInit {

  isUserAuthenticated = true;
  authSubscription : Subscription;

  constructor(private authEvent: AuthEventSvc) { }

  ngOnInit() { 
    this.authSubscription = this.authEvent.authListener().subscribe(state => {
      this.isUserAuthenticated = state;
    })
  }

  ngOnDestroy(){
    this.authSubscription.unsubscribe(); // make sure to unsubscribe
  }

}

You should also read about how change detection works and how NgZone is used in Angular to get more clarity as these topics require a long article for explanation.您还应该阅读有关更改检测的工作原理以及如何在 Angular 中使用NgZone以获得更清晰的信息,因为这些主题需要一篇很长的文章来解释。 I am just giving you some breadcrumbs to help you understand better :)我只是给你一些面包屑来帮助你更好地理解:)

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

相关问题 在ngFor循环中使用ngIf条件的Angular like按钮实现 - Angular like button implementation using ngIf condition inside ngFor loop 角度ngIf条件ngFor用于显示类似按钮 - angular ngIf condition inside ngFor for to display like button Handlebars if 语句条件显示基于membershipID的内容 - Handlebars if statement condition show content based on membershipID 根据用户位置动态更改页面内容 - dynamically change page content based on users location 如何使用* ngIf条件显示默认的null值按钮,条件是使用Mysql Node.js在* ngFor循环中显示喜欢,不喜欢和默认按钮 - How to show default null value button in angular using *ngIf condition for like, dislike and default buttons inside *ngFor loop using Mysql Node.js 将导航栏 LOGIN 更改为 LOGOUT - Change navbar LOGIN to LOGOUT 根据容器环回更改允许的内容类型-组件存储 - Change allowed content types based on container loopback - component storage 使用ngIf else角度比较两个数组值 - angular comparing two array values using ngIf else to show button Angular 根据其他选择更改将选择值更改为 null - Angular changing a select value to null based on other select change 如何根据 express 和 React 中的字段更改项目的状态/条件 - How to change an item's status/condition based on its field in express and react
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM