[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;
  }

 

 

 

 

posted @   Zhentiw  阅读(350)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-10-09 [TypeScript] Distinguishing between types of Strings in TypeScript
2015-10-09 [Javascript] Array - join()
2015-10-09 [Javascript] Array - Conact
点击右上角即可分享
微信分享提示