如果你想保持你的代碼清潔和維護,而不必布爾標誌所有的地方,這將是最好使用的服務(也許叫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