【发布时间】:2020-04-06 23:43:19
【问题描述】:
我从一个组件调用这个modal.service.ts
export class ModalService {
serviceText: boolean = true;
toggleServices() {
this.serviceText = !this.serviceText;
console.log('test', this.serviceText);
}
}
注入到options.component.ts下面...
import { Component, OnInit, Input } from '@angular/core';
import { ModalService } from '../modal.service';
@Component({
selector: 'app-options',
templateUrl: './options.component.html',
styleUrls: ['./options.component.css'],
providers: [ModalService]
})
export class OptionsComponent implements OnInit {
serviceText: boolean = false;
constructor(private modalService: ModalService) { }
ngOnInit() {
}
services() {
this.modalService.toggleServices();
}
}
options 组件的 HTML 如下,并且有一个 click 监听器...
<div class="tooth" >
<img src="../../assets/tooth-brush.png" alt="tooth-brush" (click)='services()' style='cursor: pointer;'>
<h5 (click)='services()' style='cursor: pointer;'>Services</h5>
<app-services *ngIf="serviceText"></app-services>
</div>
options.component.ts 中的services() 被调用,进而调用modal.service.ts 中的toggleServices()
控制台会记录“测试”以及 True 或 False,这是预期的行为。
但是,
options.component.html 中的 <app-services *ngIf="serviceText"></app-services> 没有像我预期的那样在显示或隐藏之间切换。
谁能明白为什么这不起作用?
提前致谢。
【问题讨论】:
-
serviceText在服务和组件中都定义,选择一个或让组件在模板中指向服务或创建属性。 -
请记住,在两个不同的类中有两个名为 serviceText 的字段就像有两个人叫 Steve,一个在纽约,一个在西雅图。仅仅因为纽约史蒂夫把四分之一放在他的口袋里并不意味着西雅图史蒂夫现在把它放在口袋里。事实上,它的意思正好相反。
标签: angular angular8 angular-services angular-ng-if