Angular cast select value to int - forms

I have a form with different selects like :
<select [(ngModel)]="selected.isConnected" (ngModelChange)="formChanged()" name="etat" id="etat" class="form-control">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>
My backend expect to receive an int in the "isConnected" attribute. Unfortunately as soon as I change the value of the select the attribute is cast to a string :
{
isConnected : "0", // 0 expected
}
For standard <input> I could use type="number" but for a <select> I'm clueless.
Is there a way to force angular 2 to cast the data to int ?

Use [ngValue] instead of "value":
<select [(ngModel)]="selected.isConnected" id="etat">
<option [ngValue]="0">Not connected</option>
<option [ngValue]="1">Connected</option>
</select>

If you want cast it within formChanged() method (Which you haven't provided yet).
You should use + symbol as shown below,
formChanged(): void {
selected.isConnected = +selected.isConnected;
...
}

No, sadly you're forced to parse it on your own in the formChanged() method, since you always get a string back from the select.
You could try it with something like this:
formChanged(): void {
selected.isConnected = parseInt(selected.isConnected);
// ...
}

You can send a Number variable to select and assign the value for that select element. Then if you want to capture the value when it changes, you can add (change) event to select and retrieve the value as shown below.
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `<select value="{{isConnected}}" (change)="printConnected($event.target.value)" name="etat" id="etat" class="form-control">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>
<div *ngIf="changed">You've selected {{isConnected}}<div>`
})
export class AppComponent {
isConnected : number = 1;
changed : boolean = false;
printConnected(value){
this.isConnected = value;
this.changed=true;
}
}
You can view an example at http://plnkr.co/edit/xO2mrTdpTGufkgXqdhYD?p=preview

I am using reactive bindings and do not want to use [(ngModel)]. Instead I created a piped observable that uses JSON.parse(value) (because +value doesn't handle "null"):
*.component.html:
<div class="col-lg-4 form-group">
<label>Group Type</label>
<select class="form-control" (change)="groupType$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let groupType of filterData.groupTypes" [value]="groupType.id">{{groupType.label}}</option>
</select>
</div>
<div class="col-lg-4 form-group" *ngIf="filteredGroups$ | async as groupOptions">
<label>Group</label>
<select class="form-control" (change)="group$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let group of groupOptions" [value]="group.id">{{group.label}}</option>
</select>
</div>
<div class="col-lg-4 form-group">
<label>Status</label>
<select class="form-control" (change)="status$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let status of filterData.statuses" [value]="status.id">{{status.label}}</option>
</select>
</div>
*.component.ts:
group$ = new BehaviorSubject<string>(null);
groupId$ = this.group$.pipe(
map((groupId: string) => JSON.parse(groupId) as number)
);
groupType$ = new BehaviorSubject<string>(null);
groupTypeId$ = this.groupType$.pipe(
map((typeId: string) => JSON.parse(typeId) as number)
);
status$ = new BehaviorSubject<string>(null);
statusId$ = this.status$.pipe(
map((statusId: string) => JSON.parse(statusId) as number)
);

[ngValue] is intended for objects. It generates an artificial option value even for numeric constants. For those who might be concerned about tests or readability, you can expand two way binding microsyntax
<select [ngModel]="selected.isConnected"
(ngModelChange)="selected.isConnected=$event && +$event" id="etat">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>

Related

insert data if not exist in the column using Laravel elequant

I'm developing a doctor's appointment laravel project. the condition is if a user fixes an appointment they can't able to fix the appointment for the same doctor at the same date and time. I tried with firstOrCreate method but doesn't match my condition. here are my conditions
1.if doctors_id AND date AND time already exist then shouldn't insert the data
2.if doctors_id OR date OR time, any three of this already exist then can insert the data
3.if all fields already not exist then insert data
here are the code snippets
In view
<div class="card-body">
<form action="appointment" method="post">
{{ #csrf_field() }}
<select name="doctors" id="" class="form-control">
#foreach ($docList as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
</select><br><br>
<input type="date" name="date" id="" class="form-control">
<br><br>
<select name="time" class="form-control">
<option value="9-10AM">9-10AM</option>
<option value="10-11AM">10-11AM</option>
<option value="1-2PM">1-2PM</option>
<option value="2-3PM">2-3PM</option>
<option value="3-4PM">3-4PM</option>
</select>
<button type="submit" class="btn btn-primary">Fix Appointment</button>
</form>
</div>
In controller
public function store(Request $request)
{
$uId = Auth::id();
$fixAppointment = Appointment::firstOrNew(['doctors_id'=>$request->doctors,'date'=>request('date')],['time'=>request('time')]);
$fixAppointment->users_id = $uId;
$fixAppointment->save();
}
Here I sorted out the issue by using where condition
In controller
$appointment = Appointment::where('date', '=', request('date'))->where('time','=',request('time'))->where('doctors_id','=',request('doctors'))->first();
if ($appointment === null)
{
$fixAppointment = New Appointment;
$fixAppointment->doctors_id = $request->doctors;
$fixAppointment->users_id = $uId;
$fixAppointment->date = $request->date;
$fixAppointment->time=$request->time;
$fixAppointment->save();
}
here is the link which I referred to find this solution.

Angular2 reactive forms select how to set invalid?

I use reactive forms within my app. In a certain form I want to display a required (Validators.required) select like this:
<select class="form-control"
[id]="dformControl.key"
[formControlName]="dformControl.key"
[multiple]="dformControl.multiple">
<option *ngIf="!dformControl.value"
value="undefined">
Choose ...
</option>
<option *ngFor="let opt of dformControl.options"
[value]="opt.value"
[selected]="dformControl.value == opt.value">
{{opt.label}}
</option>
</select>
The problem is whether I use value="undefined" or value="" the form control still is set to valid because it got a value. Do not present the value attribute results in value="Choose ...".
Am I using select with reactive forms in a false way or how would I be able to make the option "Choose ..." being not valid??
Assigning initial value of select control to null will do the trick. Try below,
model_property = null
....
this.fb.group({
....
'control_key' : [this.model_property, Validators.required]
...
})
Check this Plunker!!, Look into app/reactive/hero-form-reactive.component.ts file.
I updated the Plunker to include below and it seems to be working,
<select id="power" class="form-control"
formControlName="power" required >
// see the value is set to empty,
<option value="">Choose...</option>
<option *ngFor="let p of powers" [value]="p">{{p}}</option>
</select>
Hope this helps!!
What I do is add a blank option and when that is selected since there is no value it is not valid.
<select class="form-control"
[id]="dformControl.key"
[formControlName]="dformControl.key"
[multiple]="dformControl.multiple">
<option></option>
<option *ngFor="let opt of dformControl.options"
[value]="opt.value"
[selected]="dformControl.value == opt.value">
{{opt.label}}
</option>
</select>

Angular 2 Template Driven Forms - Array Input Elements

I have been struggling for 1 and half day and still couldn't find any solution to the problem. I am working on simple form which has select and checkboxes element.When I try submitting the form I do not get the values of select and checkboxes but rather I just get true in the console.
I am working on template driven form.
<form (ngSubmit)="addSubcontractor(subcontractorForm)" #subcontractorForm="ngForm">
<h5>Type :</h5>
<div class="form-group">
<div *ngFor="let contractor_type of contractor_types;let i = index;" class="pull-left margin-right">
<label htmlFor="{{ contractor_type | lowercase }}">
{{ contractor_type }} :
</label>
<input type="checkbox" name="_contractor_type[{{i}}]" [value]="contractor_type" ngModel>
</div>
<div class="form-group">
<select class="form-control costcodelist" name="_cc_id[]" multiple="true" ngModel>
//When I put ngModel on select I just keep getting error
//TypeError: values.map is not a function
<option *ngFor="let costcode of costcodes" [selected]="costcode.id == -1" [value]="costcode.id">{{ costcode.costcode_description }}</option>
</select>
</div>
</form>
Component Section
export class SubcontractorComponent implements OnInit, OnDestroy {
private contractor_types = ['Subcontractor', 'Supplier', 'Bank', 'Utility'];
constructor(private costcodeService: CostcodeService,
private subcontractorService: SubcontractorService) {
this.subcontractorService.initializeServices();
}
ngOnInit() {
this.costcode_subscription = this.costcodeService.getAll()
.subscribe(
(costcodes) => {
this.costcodes = costcodes;
});
}
addSubcontractor(form: NgForm) {
console.log(form.value);
}
}
When I remove ngModel from select element the code runs fine and When I submit the form I get the following output.
_contractor_type[0]:true
_contractor_type[1]:true
_contractor_type[2]:true
_contractor_type[3]:""
I do not get the checkboxes values as well the selected options from select element.
Your comments and answer will appreciated a lot.
Thanks
Here is a simple selection that i use with my Template driven form.
<form #f="ngForm" (submit)="addOperator(f.valid)" novalidate>
<label>Name</label>
<input [(ngModel)]="operator.name" name="name">
<label >Service</label>
<select #service="ngModel" name="service" [(ngModel)]="operator.service">
<option *ngFor='let service of services' [ngValue]='service'>{{service.name}}</option>
</select>
<label >Enabled</label>
<label>
<input type="checkbox" name="enabled" [(ngModel)]="operator.enabled">
</label>
<button type="submit">Create Operator</button>
</form>
.ts
operator: Operator;
ngOnInit() {
this.operator = <Operator>{}; // // Initialize empty object, type assertion, with this we loose type safety
}
addOperator(isValid: boolean) {
if (isValid) {
this.operatorsService.addOperator(this.operator).then(operator => {
this.goBack();
});
}
}
Also im importing this
import { FormsModule, ReactiveFormsModule } from '#angular/forms';

Change form action according to select option

I have a simple form:
<form name="simple" id="simple" method="post" action="X.php">
<select name="select">
<option value="none"> Select </option>
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
</select>
</form>
I want X (X.php) to change with option values.
For example, when user selects 1st, it should change to 1.php.
Is it possible?
Yes you can, example with jquery is as follows:
$("#selectID").change(function() {
var action = $(this).val();
$("#simple").attr("action", action + ".php"); // Can also use .prop("action", action + ".php");
});

jQuery addClass using input select

Im a bit of a jQuery novice.
I have 5 options in a drop down menu.
I want to add a class in a div depending on which option is selected.
This class will then change the layout of the content using CSS.
Here is an example if it helps!
Thanks
<form>
<select>
<option id="1">layout 1</option>
<option id="2">layout 2</option>
<option id="3" selected>layout 3</option>
<option id="4">layout 4</option>
<option id="5">layout 5</option>
</select>
<div class="3">styled content</div>
</form>
You can use the ".attr()" to set the class attribute of the div onchange.
You're best to change the option id to value first. then:
$("select").change(function() {
$("div").attr("class", $(this).val());
});
(EDIT) Change it to:
$("select#np_blog_layout").change(function() {
$("div#changebox").attr("class", $(this).val());
});
What 'rudeovski ze bear' said, but if you still want to set it to the div's class to the selected elements id, here it is.
$('select').change(function() {
$('div').attr('class', $(this).attr('id'));
});
First off, you don't have to use id to your options. Put the values in value attribute. Put ID to your div and select so you can select them using jQuery.
<form>
<select Id="selectElement">
<option value="1">layout 1</option>
<option value="2">layout 2</option>
<option value="3" selected>layout 3</option>
<option value="4">layout 4</option>
<option value="5">layout 5</option>
</select>
<div id="styledContent" class="3">styled content</div>
</form>
On JS
//Attach event handler to select element's onchange event
$('#SelectElement').bind("change",changeStyle);
//The event handler
function changeStyle()
{
//Set class to selected value
$('#styledContent').class($('#SelectElement').val());
}