How to add validation to ngbDropdownMenu in Angular? - html

I have a form with couple of dropdowns which looks like this:
<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
<button type="button" class="btn btn-outline-primary w-100 dropdown-toggle" id="operatorDropdown"
ngbDropdownToggle>{{operator.name ? operator.name : 'Select your operator' | translate}}</button>
<div ngbDropdownMenu aria-labelledby="dropdownExample" class="w-100 mb-3" #dropdownmenu >
<button type="button" *ngFor="let option of operators" class="dropdown-item" (click)="operator = option"
[ngClass]="{'active':operator.name === option.name}">{{option.name}}</button>
</div>
</form>
I'm having a tough time adding a simple validation to this dropdown. I want to display an error if no option is selected after pressing Submit button. Tried various validation examples on angular but none of them seems working with this kind of dropdown(without <input> etc.)
Also tried something like this, but I believe it is far from working properly.
<div *ngIf="f.controls.operatorDropdown?.errors">Error message goes here. </div>

I've managed to create the solution myself. I made that before submitting, my component would check if the operator.name is undefined(not selected). If it was, it would unhide the error message, if not it would just proceed and submit the form.
Also added the validation to (click) button event, so after the error is shown if the user chooses the operator it would validate that the operator.name is not undefined anymore and would hide the error message.
I'll share my final version, feel free to comment.
component.html
<form name="form" #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
<div ngbDropdown [className]="!isOperatorEmpty ? 'u-mw-300p u-mw-xs-100' : 'u-mw-300p u-mw-xs-100 is-invalid'">
<button type="button" class="btn btn-outline-primary w-100 dropdown-toggle" id="operatorDropdown"
ngbDropdownToggle>{{operator.name ? operator.name : 'Select your operator' | translate}}</button>
<div ngbDropdownMenu aria-labelledby="dropdownExample" class="w-100 mb-3">
<button type="button" *ngFor="let option of operators" class="dropdown-item" (click)="operator = option;validateOperatorDropdown()"
[ngClass]="{'active':operator.name === option.name}">{{option.name}}</button>
</div>
</div>
<div class="invalid-feedback u-mw-300p u-mw-xs-100" [hidden]="!isOperatorEmpty">{{"Please select operator." | translate}}</div>
</form>
component.ts
validateOperatorDropdown() {
if (this.operator.name === undefined) {
this.isOperatorEmpty = true;
} else {
this.isOperatorEmpty = false;
}
}
onSubmit(f: FormsModule) {
this.validateOperatorDropdown()
if (!this.isOperatorEmpty) {
//continue
}
}

Related

How to handle error when id value of table is null when using Modal confirm delete?

so i have modal to confirm delete action, but when the tabel data is null / dont have any data, got have an error because i dont have id to call? but if i have more than 1 data my delete modal code is works perfectly.. an error occurs when I delete the last data in the table.
i have already try :
the error message is :
Undefined variable $listproduct on --> index.blade.php)
Possible typo $listproduct
Did you mean $listproducts?
my loop function is #foreach($listproducts as $listproduct)
this is my button :
<td>
<a href="#" class="btn btn-danger delete"
data-toggle="modal"
data-target="#deleteModal"
productid="{{$listproduct->id}}"> Delete
</a>
</td>
this is my modal :
<!-- Delete Warning Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="Delete" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Delete Contact</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="{{ route('products.destroy', $listproduct->id ) }}" method="post">
#csrf
#method('DELETE')
<div class="modal-body">
<label for="id">
<input id="id" name="productid">
</label>
<h5 class="text-center">Are you sure you want to delete this contact?</h5>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-sm btn-danger">Yes, Delete Contact</button>
</div>
</form>
</div>
</div>
</div>
<!-- End Delete Modal -->
this is my script to get ID ( I use this when i write this code :
<form action="{{ url('delete', 'id' ) }}" method="post">
but still not works
) :
$(document).on('click','.delete',function(){
let id = $(this).attr('productid');
$('#id').val(id);
});
this is my Product Controller :
public function destroy($id): RedirectResponse
{
$deleteads = Product::findOrFail($id);
$deleteads->delete();
return redirect('products');
}
and this is my route (iam using Resource):
Route::group(['middleware' => ['auth']], function() {
***Route::resource('products', ProductController::class);***
Route::delete('/selected-products', [ProductController::class, 'deleteSelectedItem'])->name('products.deleteSelected');
});
First, you can't use your own productid attribute in HTML, thus you should use data attribute you save your information.
Second, your form in the modal doesn't get it's action attribute updated and thus only One product ID remains in the action attribute.
Try putting a # in the action first, and then when an item is clicked to be deleted, use JQuery to update your form's action and put the proper URL and the ID of the product.
Your ID should be saved in data attribute like below:
<td>
<a href="#" class="btn btn-danger delete"
data-toggle="modal"
data-target="#deleteModal"
data-productid="{{$listproduct->id}}"> Delete
</a>
</td>
Form in the modal:
<form action="#" method="post" id="delete_product_form">
#csrf
#method('DELETE')
<div class="modal-body">
<label for="id">
<input id="id" name="productid">
</label>
<h5 class="text-center">Are you sure you want to delete this contact?</h5>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-sm btn-danger">Yes, Delete Contact</button>
</div>
</form>
JQuery code for handling the form's action attribute update:
$(document).on('click','.delete',function(){
let id = $(this).data('productid');
$('#delete_product_form').attr('action', '/products/' + id);
});

Enable and disable submit button depends the value of Viewbag

I am trying to Enable or Disable the submit button depends the value of Viewbag.IsBtnEnabled. If Viewbag.IsBtnEnabled = 'Y' or Viewbag.IsBtnEnabled=null it should be enabled else the submit btn should be disabled. My code is working except null value. Here is my code
<div class="center-block col-sm-6">
<button type="submit" class="btn btn-primary form-control" id="btnSave"
name="submit" #(ViewBag.IsBtnEnabled == "Y" ? "" : "disabled")>
Save
</button>
</div>
If Viewbag.IsBtnEnabled = 'Y' or Viewbag.IsBtnEnabled=null it should be enabled else the submit btn should be disabled.
To achieve the requirement, you can try following code snippet.
<div class="center-block col-sm-6">
<button type="submit" class="btn btn-primary form-control" id="btnSave"
name="submit" #((ViewBag.IsBtnEnabled == "Y" || ViewBag.IsBtnEnabled == null) ? "" : "disabled")>
Save
</button>
</div>

How can I disable a Submit button, until after legitimate date is entered in an input date field?

I have a form that is used as a filter. This is the code for the date input field.
<label>Date:</label>
<input type="text" id="dateFilter"
ng-model="gridFilters.dateFilter"
placeholder="MM/DD/YYYY"
ng-disabled="loadingData" />
<span class="glyphicon glyphicon-calendar" style="width: 30px"></span>
When the angular controller initializes, the gridFilters.dateFilter value is set to undefined and should not default to anything. This is the correct behavior.
This is the code for my submit button. I'd like for the button to remain disabled until a user selects/enters a valid date.
<button type="button"
class="btn btn-success pull-right"
style="top: -5px; margin-left: 20px"
ng-click="filter()"
ng-enabled="gridFilters.dateFilter!== null && gridFilters.dateFilter!== undefined && Date.parse(gridFilters.dateFilter)"
ng-hide="session.Status !== 0">
Search
</button>
As you can see, I've made multiple attempts at checking the value of the gridFilters.dateFilter value. None of this works. Specifically, when I load the page, my button is enabled as if everything is if a proper date has been entered into the selector. How can I test if the date value is, in fact, a date? Also, this must work in Internet Explorer. I doubt this will make a difference, but IE is our corporate, preferred browser.
You need to use ng-disabled - there is no HTML attribute called enabled.
And try this:
<button type="button"
class="btn btn-success pull-right"
style="top: -5px; margin-left: 20px"
ng-click="filter()"
ng-disabled="gridFilters.dateFilter === null || gridFilters.dateFilter === undefined || Date.parse(gridFilters.dateFilter)"
ng-hide="session.Status !== 0">
Search
</button>
This ng-disabled="gridFilters.dateFilter === null || gridFilters.dateFilter === undefined" is working 100%
But for the Date.parse(gridFilters.dateFilter) I'm not sure if it will work or not.
Another approach is :
<form name="dataForm" novalidate ng-submit="submitForm()">
<input type="date" name="date" class="form-control" required
ng-model="gridFilters.dateFilter">
<button type="submit"
class="btn btn-success pull-right"
style="top: -5px; margin-left: 20px"
ng-click="filter()"
ng-disabled="dataForm.$invalid"
ng-hide="session.Status !== 0">
Search
</button>
</form>

How disable button after submit

I develop a form to add users, the form works, but the problem is
when click on the button submit two successive times, the method add two users, I want the button submit (add) disable after click directly ( I work with angular 5)
HTML Code :
<form [formGroup]="addfrm">
...
...
<div style="text-align:center">
<button class="btn btn-primary" (click)="processAdd()" [disabled]="addfrm.invalid">add</button>
<button data-dismiss="modal" class="btn btn-default">cancel</button>
</div>
</form>
You can define a field within your component and set it to true when submitted.
<button class="btn btn-primary" (click)="processAdd()" [disabled]="addfrm.invalid || submitted">add</button>
within component
export class MyComponent {
submitted = false;
...
processAdd() {
this.submitted = true;
this.someService.post(this.addForm).subscribe(result => {
this.submitted = false; // reset it on response from server
});
}
}
You can try with ngForm directive :
<form [formGroup]="addfrm" #myform="ngForm">
<div style="text-align:center">
<button class="btn btn-primary" (click)="processAdd()" [disabled]="myform.submitted">add</button>
<button data-dismiss="modal" class="btn btn-default">cancel</button>
</div>
</form>

How to retrieve the value of ng-input in Angular 6

I'm using Angular 6 and the module ngx-chips to use ng-input field, so this is the HTML template:
<div class="form-group container">
<div class="row">
<div class=" col-sm-12">
<label for="FormControlAlias"
class="col-sm-2 col-form-label float-left">Alias</label>
<div class="col-sm-8 float-left" >
<tag-input #alias [(ngModel)]="aliasList"
[secondaryPlaceholder]="'Enter the project aliases'"
[placeholder]="'Enter an alias'"
[modelAsStrings]="true"
name="alias" [separatorKeyCodes]="[188]" > </tag-input>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-primary"
(click)="addAlias(alias.value);>Add</button>
Here is the function I call by clicking the button:
addAlias( alias: Array<string>): void {
console.log(alias.value);
}
in the console I get this error :
ERROR TypeError: "alias is undefined"
I want to get the value of #alias and make a post request into the database, but I can't retrieve the value.
You have to define aliasList as a variable in your class.
After you can retreive the value with :
addAlias(): void{
console.log(this.aliasList);
}
You need not send alias value from template. You already have those values in aliasList set via ngModel. Just use that.
addAlias() {
console.log(this.aliasList);
}
template
<button type="button" class="btn btn-primary"
(click)="addAlias()">Add</button>