简体   繁体   English

Angular:使用 *ngIf 隐藏组件不起作用

[英]Angular: hiding a component with *ngIf doesn't work

I have just started with Angular and have already faced an issue: a button actually toggles the variable I need ( show ) but it doesn't affect the course.component我刚刚开始使用Angular并且已经遇到了一个问题:一个按钮实际上切换了我需要的变量( show ),但它不会影响 course.component

course.component must show app-csgo-course , boolean show is true because the component is visible, but after it toggles in navbar.component , nothing changes. course.component必须显示app-csgo-course ,布尔值show为真,因为组件是可见的,但是在它在navbar.component切换后,没有任何变化。

<app-csgo-course *ngIf="show"> </app-csgo-course>

import { NavbarComponent } from './../navbar/navbar.component';
import { Component, OnInit} from '@angular/core';
import { CourseService } from 'src/app/course.service';


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

  constructor() { }

  ngOnInit(): void { }

  service = new CourseService;
  show = this.service.GetShow();
}

In navbar.component there's a button which toggles the "show" variablenavbar.component 中有一个按钮可以切换“show”变量

      <button (click)="ToggleShow()" >
        <li class="nav-item active" id="csgo-logo">
          <a href="#">
            <img class="game-logo" src="assets\img\csgo-logo.png" title="Counter Strike: Global Offensive">
            <!-- <a>CS:GO <span class="sr-only">(current)</span></a> -->
          </a>
        </li>
      </button> 
import { CourseService } from 'src/app/cheat.service';
import { Component, OnInit, Input, Output, } from '@angular/core';

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

  service = new CourseService;
  show = this.service.GetShow();

  ngOnInit(): void {
    
  }

  public ToggleShow() {

    this.service.show = this.service.ToggleShow();
    console.log(this.service.show);
    return this.service.show;
  }
}

The course.service file course.service文件


@Injectable({
  providedIn: 'root'
})
export class CourseService {

  show: boolean = true;

  GetShow() {
    return this.show;
  }

  ToggleShow() {
    return this.show = !this.show
  }

  constructor() { }
  }
}

Would appreciate your help!感谢您的帮助!

Since you are new to Angular, let me break it down for you.由于您是 Angular 的新手,让我为您分解一下。

  1. You need to create a BehaviorSubject to capture the event of toggle (this is called reactive programming which is a achieved using RxJS in Angular ).您需要创建一个BehaviorSubject来捕获切换事件(这称为反应式编程,这是在Angular使用RxJS实现的)。

  2. Do not use new for a service, rather inject it in constructor.不要将new用于服务,而是注入构造函数。

course.service课程.服务

@Injectable({
  providedIn: 'root'
})
export class CourseService {

  private show: boolean = true;
  private toggle$ = new BehaviorSubject<boolean>(true);

  constructor() { }

  toggleEvent() {
    return this.toggle$.asObservable();
  }

  toggleShow() {
    this.show = !this.show
    this.toggle$.next(this.show);
  }
}

in NavbarComponent导航栏组件中

import { CourseService } from 'src/app/cheat.service';
import { Component, OnInit, Input, Output, } from '@angular/core';

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

  show = boolean;

  // IMP: make sure to inject the service and not do "new CourseService;"
  constructor(public service: CourseService){}

  ngOnInit(): void {
    this.service.toggleEvent().subscribe(showFlag => {
       this.show  = showFlag;
    })
  }

  public ToggleShow(): void {
    this.service.toggleShow();
  }
}

in courseComponent课程组件

import { Component, OnInit} from '@angular/core';
import { CourseService } from 'src/app/course.service';


@Component({
  selector: 'app-course',
  templateUrl: './course.component.html',
  styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {
 
 show: boolean ;
 // IMP: make sure to inject the service and not do "new CourseService;"
  constructor(public service: CourseService){}

  ngOnInit(): void {
    this.service.toggleEvent().subscribe(showFlag => {
       this.show  = showFlag;
    })
  }
  
}

PS: I would suggest you to read about "how to unsubscribe an observable" and how it causes memory leaks. PS:我建议您阅读“如何取消订阅可观察对象”以及它如何导致内存泄漏。 Once you get some idea, you should implement that in the above provided code as well.一旦你有了一些想法,你也应该在上面提供的代码中实现它。 That's a best practice.这是最佳做法。 Happy learning.快乐学习。 Let me know if you have any more questions如果您还有其他问题,请告诉我

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

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