@Input 属性 没有被第二次更新

@Input property is not being updated second time

我正在创建一个可重用组件,它可以从任何外部组件显示,但可以使用同一组件中的函数隐藏,但不知何故,父组件中的 属性 更改不会更新子组件。

这是相同的堆栈闪电战。 https://stackblitz.com/edit/angular-hfjkmu

我需要 "Show" 按钮应该一直显示组件,我可以随时使用 "hide" 按钮隐藏组件。

您遇到问题是因为您的子组件在您的子组件范围内修改了输入值,因此父组件无法知道数据发生了变化

你的子组件

   export class ShowHideComponent implements OnInit {
      @Input('show') show: boolean;
      @Output() updateShowValue: EventEmitter<any> = new EventEmitter<
        any
        >();
      constructor() { }

      ngOnInit() {
        console.log(this.show);
      }

      hide() {
        this.updateShowValue.emit(!this.show);
      }
    }

在app.component.html

<app-show-hide [show]="show" (updateShowValue)="update($event)"></app-show-hide>

和app.component.ts

export class AppComponent implements OnInit {
  show:boolean = false;
  ngOnInit() {
    this.show = false;
    console.log(this.show)
  }
  showComp(){
    this.show = !this.show;
  }

  update(event) {
    this.show = event;
  }
}

您需要使用 Output

从子项到父项同步值
  @Input()
  show = false;

  @Output()
  showChange = new EventEmitter<boolean>();

  constructor() { }

  ngOnInit() {
  }

  hide(){
    this.show = false;
    this.showChange.emit(this.show);
  }
<app-show-hide [(show)]="show"></app-show-hide>

来自子组件的 show 属性 不指向父组件中的相同道具,因为它是原始值。 我不建议修改不属于子组件的数据(引用类型,例如:对象,数组),它会导致意外行为。

带有引用类型的在线演示(修改引用类型时要小心):https://stackblitz.com/edit/angular-vhxgpo?file=src%2Fapp%2Fshow-hide-obj%2Fshow-hide-obj.component.tsenter link description here

你需要在你的子组件中添加一个@Output,当你点击隐藏按钮时(在子组件中)你需要通知你的父组件并将show变量的值更改为false,这是通过事件发射器。 所做的更改是:

ShowHideComponent.ts

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

@Component({
  selector: 'app-show-hide',
  templateUrl: './show-hide.component.html'
})
export class ShowHideComponent {
  @Input('show') show : boolean;
  @Output('') hideEE = new EventEmitter();
  constructor() { }

  hide(){
    this.hideEE.emit(false);
  }

}

AppComponent.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {

  show:boolean  = false;

}

appComponent.html

<button type="button" (click)="show = true">Show</button>

<app-show-hide [show]="show" (hideEE)="show = $event"></app-show-hide>

堆栈闪电战 Link