nativescript-angular
nativescript-angular copied to clipboard
Error: Invalid boolean when using switch component in angular reactive forms.
From @TomaNikolov on February 20, 2019 9:13
Environment
Provide version numbers for the following components (information can be retrieved by running tns info in your project folder or by inspecting the package.json of the project):
- CLI: 5.2.0
- Cross-platform modules: 5.2.0
- Android Runtime: 5.2.0
- iOS Runtime: 5.2.0
- Plugin(s):
Describe the bug
Using switch component in angular reactive forms causes Invalid boolean error.
This is only reproducible on iOS.
To Reproduce
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
pass: new FormControl(''),
});
<GridLayout>
<StackLayout [formGroup]="profileForm" class="page">
<Label text="pass" textWrap="false"></Label>
<Switch checked="false" formControlName="pass"></Switch>
<Label text="firstName" textWrap="false"></Label>
<TextField text="" hint="" secure="false" autocorrect="false"
formControlName="firstName"></TextField>
<Label text="lastName" textWrap="false"></Label>
<TextField text="" hint="" secure="false" autocorrect="false"
keyboardType="number" formControlName="lastName"></TextField>
</StackLayout>
</GridLayout>
Sample project
Copied from original issue: NativeScript/NativeScript#6934
As a workaround, we could pass a boolean value to the formControl
https://play.nativescript.org/?template=play-ng&id=pkNHQE&v=3
@TomaNikolov the error you are getting is only because the FormControl you set for the switch is initialized with an empty string. You should leave it empty: new FormControl()
Same issue here today: I found that both formControlName and checked. has to match then everything works. Whenever the values don't match I get ERROR TypeError: Cannot set properties of undefined (setting 'onTintColor') I've also tried [attr.checked]="isChecked ? 'true' : 'false'" or [checked]="'true'" or [checked]="true" doesn't work either it won't bind it either way. This issue is only on iOS, so from my understanding the checked should be a string of 'true' or 'false' but. This is defo a bug somewhere. Only If I could bind the checked with a variable it would work. Any ideas?
UPDATE The issue seems to be when adding offBackgroundColor="#cecece" but Like this works fine <Switch formControlName="is_subscribed" color="#fff" backgroundColor="green" horizontalAlignment="center" #is_subscribedEl ></Switch> As soon I add the offBackgroudnColor property all fall apart :(
WORKAROUND:
@ViewChild('is_subscribedEl', { static: false }) switchElement!: ElementRef;
ngAfterViewInit() {
if (this.switchElement?.nativeElement) {
this.switchElement.nativeElement.offBackgroundColor = '#cecece';
}
}