【问题标题】:How to access boolean variable from one component inside app component - Angular如何从应用程序组件中的一个组件访问布尔变量 - Angular
【发布时间】:2020-01-30 12:39:15
【问题描述】:

我有一个场景,其中我有多个页面,所有表单的应用程序级别都有返回箭头图标。 我正在尝试将 app.component.html 中的后退箭头设置为所有表单中的通用。但有些表格没有后退箭头。我只需要为这些表格隐藏后退箭头。 为了隐藏某些表单的后退箭头(例如 otp.component.ts),我尝试匹配 url 字符串名称,并在用户到达该特定表单时隐藏后退箭头。这是我在 app.component 里面做的。这不起作用,因为应用程序组件仅在加载应用程序时加载一次。有没有办法实现这种情况。

可能我需要匹配 otp.component.ts 中的字符串逻辑并将布尔值传递给 app.component.html。但我不确定如何实现这一点。

非常感谢您对此的任何帮助。谢谢。

app.component.html :

 <button class="header_back" *ngIf="showBackIcon" (click)="goBack()"></button>
    <button class="header_close" *ngIf="showCloseIcon" (click)="close()"></button>

app.component.ts:
 constructor() {
    const urlPath = window.location.href; 
    if (urlPath.indexOf("/otp") > -1) {
      this.showCloseIcon=true;
      this.showBackIcon=false;
    } else {
      this.showCloseIcon=false;
      this.showBackIcon=true;
    }
}

【问题讨论】:

  • 您可以将此按钮设为子组件并在需要时使用它

标签: angular boolean components hide show


【解决方案1】:

创建一个执行路径检查逻辑并分配给服务内属性的注入服务。

然后可以通过注入构造函数在整个应用程序中访问它,以便您可以从其他组件调用它并读取 app.component 中的更新值,例如this.backArrowService.showBackIcon

新服务 back-arrow.service.ts:

@Injectable()
export class BackArrowService {
public showBackIcon: boolean;
//etc

任何组件:

import { BackArrowService } from './back-arrow.service.ts';
...
constructor(public backService: BackArrowService ) {}

/*Example of directly updating value of service property which can be accessed 
from other components that inject the service also*/
...
ngOnInit() {
this.backService.showBackIcon = true;
}

应用组件html:

//See the value change:
{{backService.showBackIcon}}

<button class="header_back" *ngIf="backService.showBackIcon" (click)="goBack()"></button>

【讨论】:

  • 你能帮我举个例子吗?该服务应该是 app.service.ts 还是应该在哪里创建该服务
  • 一项新服务,您可以随时随地创建。查看如何为 Angular 生成服务。这样,功能和属性可以在组件之间共享/访问我已经添加了更多详细信息来回答。
  • 但我的箭头图标和布尔值状态在 app.html 文件中维护。如何通过服务更新这个变量的状态。
  • 维护服务中布尔值的状态,而不是使用服务中的新属性。然后从您的应用程序组件 html 访问它,例如{{backService.showCloseIcon}}。您可以从注入服务的任何 component.ts 文件更新此属性,并从任何组件中读取它。您还可以在服务中创建一个函数并从任何组件调用它,例如this.backService.myFunction() 可以更新服务中的布尔值。
  • app.component 中的值会自动更新,如果它是从 app 组件中的组件更新的,只要它们在服务中使用相同的变量。应用程序组件将注入相同的服务,因此当在子组件中更新属性时,将使用该属性的最新值进行更新。尝试从子组件中对属性进行简单更新,并查看应用 html 中的值更新。
猜你喜欢
  • 2020-06-18
  • 1970-01-01
  • 2019-09-11
  • 2023-01-05
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
  • 1970-01-01
  • 2017-02-25
相关资源
最近更新 更多