[Angular] Refactor Angular Component State Logic into Directives

Allow the base toggle to be a tag (<toggle>) or attribute (<div toggle>). The <toggle> component has become less opinionated about the view, but has now taken on some responsibilities managing state. We’ll decouple the state management piece by moving it into the toggleProvider directive. The toggleProvider directive provides state for all the <toggle-off>, <toggle-on> and <toggle-button> components inside it.

 

For toggle component we made in previous post

@Component({
  selector: 'toggle',
  template: '<ng-content></ng-content>',
})

As you can see, it use 'ng-content' inside template which means that it doesn't actually needs a template, we can consider ToggleComponent as a directive.

 

So we can modifiy ToggleComponet to ToggleDirective:

复制代码
import { Directive, Input, Output, EventEmitter } from '@angular/core';

@Directive({
  selector: 'toggle, [toggle]'
})
export class ToggleDirective {
  @Input() on: boolean;
  @Output() toggle: EventEmitter<boolean> = new EventEmitter();

  setOnState(on: boolean) {
    this.on = on;
    this.toggle.emit(this.on);
  }
}
复制代码

So we can change the usage in app.component.html:

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

Then change all the dependencies injection for toggle-on/off/button component, the application should still works.

 

One problem for the current directive implementations is that each toggle directives are isolated:

 

Most of times, isolated directives are OK, but in some cases, if you want to share the state between two or more directives. You have to do some extra works.

 

Write ToggleProviderDirective for reference ToggleDirective.

state <-- ToggleDirective <-- ToggleProviderDirective

So ToggleDirective is managing the state, if we want to share the state, we create ToggleProviderDirective, it takes ToggleDirective as input, so that we can share one ToggleDirective thoughts multi directives.

复制代码
import { Directive, Input, Output, Host, OnChanges, SimpleChanges, Optional } from '@angular/core';
import {ToggleDirective} from './toggle.directive';

@Directive({
  exportAs: 'toggleProvider',
  selector: 'toggle, [toggle], [toggleProvider]',
})
export class ToggleProviderDirective implements OnChanges {

  @Input() toggleProvider: ToggleDirective;

  toggle: ToggleDirective = this.toggleDirective;

  constructor(
    // Reference the toggle directive on the same host element
    @Host() @Optional() private toggleDirective: ToggleDirective
  ) {
    
  }

  ngOnChanges(changes: SimpleChanges) {
    const {toggleProvider} = changes;
    if (toggleProvider) {
      this.toggle = this.toggleProvider || this.toggleDirective;
    }
  }
}
复制代码

 

Also need to change the reference for toggle-on/off/button:

复制代码
import { Component } from '@angular/core';

import { ToggleProviderDirective } from './toggle.toggleProvider.directive';

@Component({
  selector: 'toggle-button',
  template: '<switch [on]="toggleProvider.toggle.on" (click)="onClick()" ></switch>',
})
export class ToggleButtonComponent  {
  constructor(public toggleProvider: ToggleProviderDirective) {}

  onClick() {
    this.toggleProvider.toggle.setOnState(!this.toggleProvider.toggle.on);
  }
}
复制代码

 

 

 

posted @   Zhentiw  阅读(363)  评论(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工具
历史上的今天:
2017-10-10 [Angular & Unit Testing] TestBed.get vs Injector
2017-10-10 [Angular & Unit Testing] Automatic change detection
2017-10-10 [Angular & Unit Testing] Testing Component with Store
2017-10-10 [React] Use a Render Porp
2016-10-10 [Ramda] Getter and Setter in Ramda & lens
2016-10-10 [Angular2 Router] Index router
2016-10-10 [TypeScript] Using Interfaces to Describe Types in TypeScript
点击右上角即可分享
微信分享提示