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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With