zoukankan      html  css  js  c++  java
  • [Angular] Write Compound Components with Angular’s ContentChild

    Allow the user to control the view of the toggle component. Break the toggle component up into multiple composable components that can be rearranged by the app developer.

    Compound component mainly for rendering flexibility. It hides the implements detial from users, but users can freely re-order the child component order or add new component into it.

    In this post we are looking into how to apply "@ConetentChild" to do compound components. 

    This is not a recommended way, just for learning!

    So a highlevel compound component looks like:

    <toggle (toggle)="onToggle($event)">
      <toggle-button></toggle-button>
      <toggle-on>On</toggle-on>
      <toggle-off>Off</toggle-off>
    </toggle>

    For the parent component 'toggle' component, the job for it is hide implement details from the consumers. It handles the internal state. Which means 'toggle' component needs to access the state of its Children components.

    <toggle-button></toggle-button>
    <toggle-on>On</toggle-on>
    <toggle-off>Off</toggle-off>

    The way to can accomplish it is using '@ContentChild':

    @ContentChild(ToggleOnComponent) toggleOn: ToggleOnComponent;
    @ContentChild(ToggleOffComponent) toggleOff: ToggleOffComponent;
    @ContentChild(ToggleButtonComponent) toggleButton: ToggleButtonComponent;

    Listen for Child component's ouput event:

    toggle-button component has Output event call 'toggle':

    @Component({
      selector: 'toggle-button',
      template: '<switch [on]="on" (click)="onClick()" ></switch>',
    })
    export class ToggleButtonComponent  {
      @Input() on: boolean;
      @Output() toggle: EventEmitter<boolean> = new EventEmitter();
      onClick() {
        this.on = !this.on;
        this.toggle.emit(this.on);
      }
    }

    Then we can listen the Output event in 'ngAfterContentInit()' lifecycle hooks.

     ngAfterContentInit() {
        this.toggleButton.toggle.subscribe(on => {
          this.on = on;
          this.toggle.emit(on);
          this.update();
        });
      }

    Also 'toggle' component will take care to update Children components state:

      update() {
        this.toggleOn.on = this.on;
        this.toggleOff.on = this.on;
        this.toggleButton.on = this.on;
      }

  • 相关阅读:
    通过如何通过js实现复制粘贴功能
    通过localstorage和cookie实现记录文章的功能
    HTML5表单提示placeholder属性兼容IE
    html5跨域数据传递(postMessage)
    js获取当前指定的前几天的日期(如当前时间的前七天的日期)
    html5本地存储(localStorage)使用介绍
    原生js动画效果(源码解析)
    如何通过js和jquery获取图片真实的宽度和高度
    echart-图表位置改变
    echart-渐变色背景
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9745834.html
Copyright © 2011-2022 走看看