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.
source share