首页 > 解决方案 > *ngIf 没有按预期隐藏/显示组件

问题描述

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();
  }
}

选项组件的 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>

services()调用 options.component.ts中toggleServices()modal.service.ts

控制台会记录“测试”以及 True 或 False,这是预期的行为。

但,

options.component.html<app-services *ngIf="serviceText"></app-services>中的 没有像我预期的那样在显示或隐藏之间切换。

任何人都可以看到为什么这不起作用?

提前致谢。

标签: angularangular8angular-servicesangular-ng-if

解决方案


serviceText在服务和组件中都定义,选择一个或让组件指向模板中的服务或创建属性。

export class OptionsComponent implements OnInit {

  get serviceText(): boolean { return this.modalService.serviceText; }

  /* rest of code unchanged... */

推荐阅读