如何从应用程序组件内的一个组件访问布尔变量 - Angular

How to access boolean variable from one component inside app component - Angular

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

可能我需要匹配 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;
    }
}

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

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

新服务返回-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>