自定义组件接收布尔变量但不更新 HTML 中的 NgIf

Custom component receives boolean variable but does not update NgIf in HTML

我有一个自定义组件,其视图中有一个 *ngIf 并接收一个布尔变量,但 *ngIf 不起作用。这是代码:

组件

@Input('title') titleText;
@Input('backButton') backButton;
@Input('avatarImage') avatarImage;
@Input('userId') userId;
@Output('avatarClicked') avatarClicked = new EventEmitter()

titlePage: string;
img: string; 
back: boolean = false;

constructor() {}

ngAfterViewInit() {
    this.titlePage = this.titleText;
    this.img = this.avatarImage;    
    this.back = this.backButton;    
}

openPersonalData() {
    this.avatarClicked.emit({value: this.userId})
}

组件HTML

<ion-header>
    <ion-toolbar>        
        <ion-buttons *ngIf="back == true" slot="start">
            <ion-back-button text="Voltar"></ion-back-button>
        </ion-buttons>
        <ion-title>{{ titlePage }}</ion-title>        
        <ion-avatar slot="end" (click)="openPersonalData()">
            <img [src]="img">
        </ion-avatar>
    </ion-toolbar>
</ion-header>

页面使用组件

<app-header title="Chat" 
    [backButton]="true" 
    avatarImage="{{ user[0].img }}" 
    userId="{{ user[0].id }}" 
    (avatarClicked)="openPersonalData($event)">
</app-header>

有人知道我做错了什么吗?

我认为您的输入是在 ngAfterViewInit 生命周期挂钩之后设置的。重新分配一个字段也有点多余。您只需在模板中使用 backButton 输入即可。

<ion-buttons *ngIf="backButton == true" slot="start">

下面这段代码工作正常,符合您需要的逻辑:

可以查一下here:(只需要将[backButton]="true"的值改为[backButton]="false"即可看到它 showing/not 显示儿子)

父亲 HTML:

<app-header
  title="If you see this, backButton is set to true"
  [backButton]="true"
>
</app-header>

儿子 HTML:

<div *ngIf="backButton">
  {{ title }}
</div>

儿子组件 TS:

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

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html",
  styleUrls: []
})
export class HeaderComponent {
  @Input("title") title;
  @Input("backButton") backButton;
}

我认为你应该在 ngOnchnages 生命周期方法中影响你的数据值:

// 每当组件@Inputs 改变时运行

@Input('title') titleText;
@Input('backButton') backButton: boolean;
@Input('avatarImage') avatarImage;
@Input('userId') userId;
@Output('avatarClicked') avatarClicked = new EventEmitter()

titlePage: string;
img: string; 
back: boolean = false;

constructor() 




   ngOnChanges () {
        // Check if the data exists before using it
        if (this.backButton) {
             this.back = this.backButton; 
        {
    }