Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically add and remove formGroup in angular 2 custom child component

Tags:

I have a custom switch that needs to be used for both with and without forms. i.e.

custom-switch.component.html

<div class="custom-switch" [formGroup]="parentGroup">
    <input id="{{ id }}" name="status" type="checkbox"
           [checked]="checked"
           formControlName="{{ switchName }}"
           (change)="onChange($event, id)" />
    <label for="{{ id }}" class="label-default" data-toggle="tooltip" data-selector="true"
           data-title="Switch"></label>
</div>

custom-switch.component.ts

import { Component, Input } from "@angular/core";
@Component({
    selector : 'custom-switch',
    template : 'custom-switch.component.html'
})
export class CustomSwitchComponent {
    @Input('id') id : any = 'switch';
    @Input('parentGroup') parentGroup : any;
    @Input('switchName') switchName : any;

    onChange() {
        //do something
    }
}

from parent component i call the component for form child component as:

<custom-switch [parentGroup]="form" [switchName]="'switch'"></custom-switch>

I want to use:

<custom-switch></custom-switch>

and remove

[formGroup]="parentGroup" and formControlName="{{ switchName }}"

for non form child component.

How could i dynamically remove formGroup and formControlName? As it generates error when i try to use it on non form components.

like image 343
PaladiN Avatar asked Jan 04 '17 09:01

PaladiN


1 Answers

There is no way to conditionally add/remove bindings. Only the addition of attributes to the DOM can be controlled by conditions.

You can use *ngIf to switch between two elements where one has the binding and the other doesn't have one:

<custom-switch *ngIf="useForm" [parentGroup]="form" [switchName]="'switch'"></custom-switch>
<custom-switch *ngIf="!useForm"></custom-switch>
like image 66
Günter Zöchbauer Avatar answered Sep 25 '22 10:09

Günter Zöchbauer