* ng如果未按预期隐藏/显示组件

时间:2019-12-13 13:54:16

标签: angular angular8 angular-services angular-ng-if

我正在从组件中调用此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()被调用,而在toggleServices()中的modal.service.ts

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

但是

options.component.html中的<app-services *ngIf="serviceText"></app-services>并未在显示或隐藏之间进行切换。

有人可以看到为什么这不起作用吗?

谢谢。

3 个答案:

答案 0 :(得分:1)

您需要使用serviceText在组件中初始化this.modalService.serviceText,您可能会忘记这样做。

此外,由于这是您要更新的服务中的布尔值,它是原始值,因此会按值传递。

因此,每次在服务上切换serviceText时,都必须重新定义组件中的serviceText和服务中的serviceText

在组件中执行以下操作:

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() {
    this.serviceText = this.modalService.serviceText;
  }

  services() {
    this.modalService.toggleServices();
    this.serviceText = this.modalService.serviceText;
  }
}

这应该可以按预期工作。


  

这是您推荐的Sample Demo

答案 1 :(得分:1)

在服务和组件中都定义了

serviceText,在模板中选择一个或让组件指向该服务,或者在模板中创建了属性。

export class OptionsComponent implements OnInit {

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

  /* rest of code unchanged... */

答案 2 :(得分:-2)

您需要使用modalService.serviceText而不是serviceText,因为ModaService仅更新其内部变量

ts

constructor(public modalService: ModalService) { }

html

<app-services *ngIf="modalService.serviceText"></app-services>