如何从父级发送相同的值时检测@input属性中的更改

问题描述 投票:2回答:2

我研究过,他们都没有能够给我正确的解决方案。我有两个名为parentComponent和childComponent的组件。

childComponent.html

     <div *ngIf="isShowMessage">
       <p>Hey i was told by parent component to be shown Here i am !!!</p>
         <button (click)="cancel()">cancel</button>
     </div>

childComponent.ts

     _isShowMessage = false;

     @Input() set isShowMessage(value: boolean) {
          this._isShowMessage = value;
     }
      get isShowMessage(): boolean {
            return this._isShowMessage;
      }
     cancel(): void {
      this._isShowMessage = false;
      this.isShowMessage = false;
    }

ParentComponent.html

      <childComponent [isShowMessage]="isShowMessage"></childComponent>
      <button (click)="handleClick()">save</button>

ParentComponent.ts

        isShowMessage = false;
        handleClick(): void {
          this.isShowMessage = true;
         }

第1步:当我从父级单击“保存”按钮时,将显示子组件div:

     <p>Hey i was told by parent component to be shown Here i am !!!</p>

Step2:当我从子组件中单击取消按钮时,div被隐藏。 [预期行为]

第3步:当我再次从父级单击“保存”按钮时,不显示子组件div。

它是由于第二次发送的相同值真实吗?不确定...任何建议表示赞赏。

angular angular6 angular2-changedetection
2个回答
0
投票

考虑这种方法:

ParentComponent.html

<childComponent #child></childComponent>
<button (click)="handleClick(child)">save</button>

ParentComponent.ts

handleClick(child): void {
  child.isShowMessage = true;
}

0
投票

您正在从父级向子级发送ShowMessage,因此您正在对子组件进行更改。然后,如果子级中发生任何事件,请通过发送事件让父级知道,这样父级将与子级同步,如果父级在该情况下再次更改该值孩子会得到那个价值。

检查以下编辑的代码

childComponent.html

 <div *ngIf="isShowMessage">
   <p>Hey i was told by parent component to be shown Here i am !!!</p>
     <button (click)="cancel()">cancel</button>
 </div>

childComponent.ts

     _isShowMessage = false;

     @Input() set isShowMessage(value: boolean) {
          this._isShowMessage = value;
     }
    @Output() hideParentValue = new EventEmitter();
      get isShowMessage(): boolean {
            return this._isShowMessage;
      }
     cancel(): void {
     //comment this below code 
     // this._isShowMessage = false;
     // this.isShowMessage = false;

     //add this 
     this.hideParentValue.emit()
    }

ParentComponent.html

  <childComponent [isShowMessage]="isShowMessage" 
     (hideParentValue)="hideMessage()"></childComponent>
          <button (click)="handleClick()">save</button>

ParentComponent.ts

 isShowMessage = false;
        handleClick(): void {
          this.isShowMessage = true;
         }
         hideMessage():void {
          this.isShowMessage = false;
         }

如果仍有问题,那么你可以让子组件实现OnChanges接口,然后实现ngOnChanges函数并将调试器放在那里。

如果输入更改调试器应该命中..您可以通过此生命周期钩子找到问题的根本原因。

© www.soinside.com 2019 - 2024. All rights reserved.