Angular 2: Components that remove themselves from the DOM

I have one parent component with two child components ( dataset-create and dataset-detail ) in Angular2. The parent component controls which of the two components is displayed at any given time using this code in its template:

 <div [ngSwitch]="mode"> <template [ngSwitchWhen]="'create'"> <dataset-create [dataset]="dataset" (close)="onDatasetFormClose()"></dataset-create> </template> <template [ngSwitchWhen]="'detail'"> <dataset-detail [dataset]="dataset" (close)="onDatasetFormClose()"></dataset-detail> </template> </div> 

The parent component listens for an event (close) in children. When it receives it, the callback function ( onDatasetFormClose() ) is onDatasetFormClose() , which has the following code:

 private onDatasetFormClose() { this.mode = "list"; } 

This function changes the value of the mode variable. This causes both ngSwitchWhen statements to ngSwitchWhen , and therefore the currently active child component is destroyed.

In addition, FYI, this is how the template of one of the child components looks like:

 <form novalidate="novalidate"> <button type="button" (click)="onClose()">close</button> <button type="submit" (click)="onSubmit()">submit</button> <label for="dataFileD">data</label> <input id="dataFileD" type="file" (change)="onFileChange($event)"> </form> 

However, this solution looks "wrong" to me because it depends on the parent component (thus making it harder to reuse it yourself).

I guess another way to achieve a similar result would be to use a router. This solution not only sounds “too bloated for a reason,” but also suffers from the same problem as my solution above: the child component cannot be used independently.

Is it possible to remove a child component from the DOM? What is the right way to deal with such situations? Perhaps having components that remove themselves from the DOM is bad Angular2 coding practice?

Thanks in advance.

+6
source share
2 answers

I think the component requires a mother component. Components that emit an event typically require a parent component. And sometimes the components are more tightly connected or designed / needed for sharing. For example, to implement tabs, we probably need the parent component tabset in addition to the child components tab . For example, see the ng2-bootstrap tab.

Reliance on the parent component can also be a conscious design decision. For example, if we model our application using immutable application data (see Savkin blog ), we can intentionally prevent our component from changing any application data. If a delete operation is required, we can emit an event so that a higher-level component changes the application data (and then sends it back through the input property).

+4
source

Why don't you have the bloolean flag, tell show about the subcomponent. Then just change it to false when you need to. In a template, just wrap everything with

0
source

All Articles