【问题标题】:Modify component's view when something happens inside it's child当子组件内部发生某些事情时修改组件的视图
【发布时间】:2016-08-13 23:03:47
【问题描述】:

假设我有两个组件:主页和编辑器。

在主页组件,当我点击“添加帖子”按钮时,我会显示editor组件。

首页组件的视图

<button (click)="showEditor()">Show editor</button>
<editorComponent *ngIf="clicked"></editorComponent>

showEditor() 只需将clicked 变量设置为true,然后editor 组件就会出现。

编辑器组件的视图

<div class="editor">
  ...some editor stuff
  <button (click)="cancel()">Cancel</button>
</div>

单击Cancel 按钮时,我想将editor 组件隐藏在homepage 组件中。为此,我应该再次将 homepageComponent.clicked 设置为 false,但如何在另一个组件中执行此操作。你有更好的主意吗?

【问题讨论】:

    标签: javascript angular typescript components


    【解决方案1】:

    我建议向 hp-component 添加一个“clicked”值,该值将传递给 editor-component。如果值被修改,Angular 会识别并更新值并相应地查看。

    不幸的是,JavaScript 通过值传递原语,所以我们需要作弊:

    class Wrapper {
      constructor( public value: any ) { }
    }
    

    将此添加到主页组件:

    class HpComponent {
      clicked: Wrapper = new Wrapper(false);
    
      showEditor() { clicked.value = true; }
    }
    
    class EditorComponent {
      @Input() clicked: Wrapper;
    
      cancel() { clicked.value = false; }
    }
    

    并将对象传递给编辑器组件:

    <button (click)="showEditor()">Show editor</button>
    <editorComponent *ngIf="clicked.value" [clicked]="clicked"></editorComponent>
    

    免责声明:我对 angular2 还很陌生,所以这可能不是最好的答案。 AFAIK Typescript 提供泛型,您可以在包装类中实现它们。

    【讨论】:

      【解决方案2】:

      使用@Output 事件。子组件将发出一个事件,父组件通过绑定订阅。

      主页.html

      <editor (cancelClickedEvent)="cancelEvent"></editor>
      

      主页.ts

      cancelEvent(data) {
        // hide editor component
      }
      

      editor.html

      <div class="editor">
        ...some editor stuff
        <button (click)="cancel()">Cancel</button>
      </div>
      

      editor.ts 文件

      @Output
      cancelClickedEvent: any = new EventEmitter<any>();
      
      onCancelClick() {
        this.cancelClickedEvent.emit(data) // <-- data is whatever you want
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-12
        • 2022-08-10
        相关资源
        最近更新 更多