如果你想保持你的代码清洁和维护,而不必布尔标志所有的地方,这将是最好使用的服务(也许叫ToggleService
)处理切换和检查是否应该显示的东西。
例如,下面是一个简单的ToggleService
,它使您能够使用show/hide方法创建新项目,移除项目并切换项目的可见性(请记住,以下任何内容都经过测试,我简直就是写所有的飞行对这个问题 - 但是这一切似乎是合乎逻辑和应工作):
@Injectable()
export class ToggleService {
toggleMap: {[uniqueKey: string]: any} = {};
create(key: string) {
this.toggleMap[key] = null;
}
remove(key: string) {
delete this.toggleMap[key];
}
isShown(key: string): boolean {
return this.toggleMap[key];
}
show(key: string) {
this.toggleMap[key] = true;
}
hide(key: string) {
this.toggleMap[key] = false;
}
}
现在在你的组件,你可以利用该服务:
@Component({...})
export class MyComponent implements OnInit, OnDestroy {
constructor(public toggleService: ToggleService) {}
ngOnInit() {
this.toggleService.create('componentOne');
this.toggleService.create('componentTwo');
this.toggleService.create('componentThree');
}
// Clean up when parent component is destroyed to save memory
ngOnDestroy() {
this.toggleService.remove('componentOne');
this.toggleService.remove('componentTwo');
this.toggleService.remove('componentThree');
}
}
在模板:
<button (click)="toggleService.show('componentOne')">Show component 1</button>
<button (click)="toggleService.show('componentTwo')">Show component 2</button>
<button (click)="toggleService.show('componentThree')">Show component 3</button>
<componentOne *ngIf="toggleService.isShown('componentOne')"></componentOne>
<componentTwo *ngIf="toggleService.isShown('componentTwo')"></componentTwo>
<componentThree *ngIf="toggleService.isShown('componentThree')"></componentThree>
请记住,单击其中一个按钮不会隐藏另一个按钮。为此,您可能需要创建一个toggle
方法,该方法将遍历服务中的整个toggleMap
,并将所有内容都设为false,然后将唯一的一项设置为true。
我会离开,最后一位作为练习你;)
兰萨纳·您好,我想可观察到的主题将是在服务中更好地与这样的对象{childAVisible:真等} – AngularM
在'ToggleService可观察到的主题'在这里也同样适用。 – Lansana