[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; }
相关文章
- 从 Angular Component 和 Directive 的实例化,谈谈 Angular forRoot 方法的命令由来
- angular框架如何实现父子组件传值、非父子组件传值
- node、npm 、package.json、Angular Cli、webpack之间的关系(Windows环境下)
- Angular tsconfig.json 文件里的 paths 用途
- 模块化开发 Angular 应用 [含懒加载]
- Angular HTTPClient API 在 SAP 电商云中的使用
- 前端人员该怎么面试 经典Angular面试题有哪些[通俗易懂]
- 解决angular创建项目报错:setTimeout is not defined
- 关于 Angular 应用的入口
- 关于 Angular Universal 应用执行时需要 Browser API 的问题
- angular框架发展史
- Angular 项目路径添加指定的访问前缀
- Angular SSR 应用启动时的一些保护措施
- 语句使用Oracle两个WITH语句实现数据查询(oracle两个with)
- 基于豆瓣API+Angular开发的webApp