Angular 仅在某些条件下显示 DIV

Angular show DIV only on some conditions

我有一个 header.component.html 文件(这是一个共享组件),除了其他内容,我在其中添加了一个带有消息的 DIV。仅当 showMsg 属性 为真时才应显示:

<div *ngIf="showMsg" >Some message</div>

在 header.ts 文件中我定义了 属性

showMsg: boolean;

并且在构造函数中默认:this.showMsg= false;

这很好用,这意味着如果我在这里将 this.showMsg 设置为 true,消息就会显示,反之亦然。

但由于这是一个共享组件,它通过以下方式包含在 main.html 组件中:

  <app-header></app-header>

showMsg 应该依赖的后端数据仅在 main.ts 组件中。

我唯一需要的,假设 this.Year 是来自后端的 属性 - 我想要的是如果年份是 2021,然后将 showMsg 设置为 true 并显示消息,否则隐藏该共享组件中的消息。

问题是,我的解决方案不起作用:

if (this.Year === '2021')
      {this.showMsg = true; console.log(this.showMsg);}

还好说,条件OK,showMsg会被设置为true,但是header.html中的消息没有显示。似乎它忽略了来自 main.ts.

的 showMsg

在子组件中使用 @Input 属性 来设置父组件的值。

子组件控制器

import { Component, Input } from '@angular/core';

@Component({...})
export class SharedComponent {
  @Input() showMsg: boolean = false;  // <-- default when `[showMsg]` is not bound in parent
  ...
}

父组件控制器

showMsg: boolean = false;

someMethod() {
  this.someService.get('year').subscribe({
    next: (Year: any) => {
      this.showMsg = Year === '2021';
      ...
    },
    error: (error: any) => { }
  });
}

父组件模板

<app-header [showMsg]="showMsg"></app-header>

您可以像这样将 showMsg 作为输入传递给您的共享组件

<app-header [showMsg]="showMsg"></app-header>

在你的 header.component.ts 中添加

@Input showMsg: boolean = false;

查看https://angular.io/guide/inputs-outputs了解更多信息