【发布时间】:2023-04-04 04:00:02
【问题描述】:
我刚开始使用Angular 并且已经遇到了一个问题:一个按钮实际上切换了我需要的变量(显示)但它不会影响 course.component
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();
}
在 navbar.component 中有一个按钮可以切换“显示”变量
<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;
}
}
course.service 文件
@Injectable({
providedIn: 'root'
})
export class CourseService {
show: boolean = true;
GetShow() {
return this.show;
}
ToggleShow() {
return this.show = !this.show
}
constructor() { }
}
}
非常感谢您的帮助!
【问题讨论】:
-
CourseComponent.show在创建组件时设置一次,并且在您切换CourseService中的值时其值不会改变,这就是它无法按预期工作的原因。尝试重构您的代码。
标签: javascript html angular typescript rxjs