在Angular2中,我需要在父组件中显示和隐藏子组件

时间:2017-10-17 18:35:07

标签: angular typescript

在Angular2中,最好显示和隐藏子组件吗?

我有一个父组件三个子组件

默认情况下 onInit 需要隐藏所有子组件。 并且 childComponentA 需要显示父组件中按钮的单击。

流程:

我在 childComponentA 中有一个按钮,需要在click上显示 childComponentB ,而childComponentB组件有一个需要显示 childComponentC 的按钮。就像表演和隐藏的流程一样。

最好这样做吗?

可能的解决方案?

我正在考虑创建一个所有子组件订阅的服务来显示和隐藏。但不确定它是否是最佳解决方案。

父组件HTML:

dt <- as.data.frame(table(Groups))
# Subset the data for Freq > 0
subset(dt, Freq > 0)
     Ind            Sp Freq
1 deima1 P. deimaticus    5
2 deima2 P. deimaticus    5
7  eryt1   P. erythros    5
8  eryt2   P. erythros    5

2 个答案:

答案 0 :(得分:2)

如果你想保持你的代码干净和可维护,并且没有遍布整个地方的布尔标志,最好使用一个服务(可能称为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。

我会留下最后一点作为练习;)

答案 1 :(得分:1)

我选择基于组件的设计。在我看来,事件驱动设计并不酷,因为很难跟踪哪个组件与哪个事件发布者进行交互。

Stackblitz example

compound