ng-multiselect-dropdown - programmatically clear selected items not visually working - html

I am using ng-multiselect-dropdown when clicking the deselect option within the object itself the dropdown clears the selected items (visually and variable
When programmatically clearing the selectedItems the variable array itself is cleared but the selected items within the visual portion are still selected. If you were to then click within the object the values would no longer be available as a selection but visually the object does not clear.
I've tried a few options to clear I'll show here below. I've also tried to put it into a form and then manually clearing the control.In any scenario I've tried when not deselectingAll from the dropdown itself the visual portion remains cached and the selectedItems is empty.
Form:
<form [formGroup]="multiselect" (ngSubmit)="onSubmit()">
<div>
<ng-multiselect-dropdown [placeholder]=""
[settings]="settings"
[data]="propertiesCharUnique"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)"
(onDeSelect)="onDeSelect($event)"
(onDeSelectAll)="onDeSelectAll($event)"
formControlName="multi"
[(ngModel)]="selectedItems"
>
</ng-multiselect-dropdown>
<input type="submit" value="Load Targets" />
</div>
#ViewChild('multiselect') multiSelect: any;
multiselect = this.formBuilder.group({
});
public reset(){
this.multiselect.get("multi")?.setValue([]);
this.multiselect.get("multi")?.reset()
this.selectedItems = [];
}

I removed the dropdown from the form and now ngModel binds properly.
<div>
<ng-multiselect-dropdown
[placeholder]="'Click here to select'"
[settings]="settings"
[data]="propertiesCharUnique"
[(ngModel)]="selectedItems"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)"
(onDeSelect)="onDeSelect($event)"
(onDeSelectAll)="onDeSelectAll($event)" >
</ng-multiselect-dropdown>
<input type="submit" (ngSubmit)="onSubmit()" value="Load Targets" />
</div>

Related

Kendo checkbox toggle true and false states not working properly

I'm trying to get it so when one or more checkbox is clicked, I'm able to get a button to appear. I would like the toggle function to work if one or more checkbox is clicked, but instead, it will turn on when I select one checkbox, then turn off during the next selection. I'm sure I've got a couple of unnecessary properties added into here as well, but not too concerned about that. Any help would be appreciated.
HTML: Button
<button class="btn btn-primary"
*ngIf="switchCase" style="float:right"
>Save</button>
HTML: Checkbox Column
<kendo-grid-column field="checkbox" editor="boolean">
<ng-template kendoGridCellTemplate let-dataItem id="flexSwitchCheckChecked"
>
<input type="checkbox" (click)="toggleButton(dataItem, 'checkbox'
[checked]="dataItem.checkbox"
[width]="40"
>
TS: Button click method
public switchCase: boolean = false;
toggleButton() {
this.switchCase = !this.switchCase;
pass an event to your function then access its value from typescript class:
Step1(pass an $event):
on *ngFor tag level add an index var
<div *ngFor="let item of items;let i = index" >
<input type="checkbox" (change)="toggleButton($event,i)">
</div>
Step1(get its value):
toggleButton($event,i) {
let newValue = $event.target.value;
// this.switchCase =newValue;
this.items[i].checked = newValue;
}

Prevent expand on click on prime ng accordion

I have an primeng accordion and the accordion header has a checkbox control . Whenever i check/uncheck checkbox , the accordion tab is getting open/closed automatically
Is there any way to prevent expand/collapse on click on checkbox ? It should expand/collapse on header other than check/uncheck check box ?
This is happening due to Event Bubbling. For this need to stop eventPropagation by calling stopPropagation() of MouseEvent.
Accordion html code sample
<p-accordion>
<p-accordionTab header="Godfather I" [selected]="true">
<p-header>
<span>Godfather I
<input type="checkbox" (click)="onClick($event)">
</span>
</p-header>
Some Text
</p-accordionTab>
</p-accordion>
Corresponding component ts code.
onClick($event: MouseEvent){
$event.stopPropagation();
}
For Reference added stackblitz code sample.
This is how I solved this issue. This is happening because of Event Bubbling. So when you click on child element. Event propagate to its parent and so on. So Just use stop propagation on event. It will prevent the click event on your accordion. Below code for your reference.
Accordian with Check box code I used (onChange) method.
<p-accordionTab>
<p-header>
<div class="ui-g" style="width:250px;margin-bottom:10px">
<div class="ui-g-12"><p-checkbox name="group1" #ck value="New York" label="New York" [(ngModel)]="selectedCities" (onChange)="checkChange($event)" inputId="ny"></p-checkbox></div>
</div>
</p-header>
</p-accordionTab>
component.ts
selectedCities: string[] = [];
//Simply you have to to stop propogation here.
checkChange(e:any){
console.log(e); // true or false.
event.stopPropagation(); // component will have direct access to event here.
}

How to refresh/reload a parent component onclick of child component submit button in angular 6?

My parent component ts file contains this code:
openNewModal(): void {
this.$modal.show(CategoryAddModalComponent)
.subscribe(r => {
});
location.reload();
}
My child component html:
<form action="">
<label>Enter Category</label>
<input name="cate" type="text">
<input name="category" type="text">
<button class="common-btn btn-cancel" (click)="modal.hide();l>Cancel</button>
<button class="common-btn btn" type="submit" (click)="fun_addcategory()">Submit</button>
</form>
So using this openNewModal() function Im calling my child component model. Now On submit of my child component I need to reload my parent component file. If I try to call location.reload in this function, my child component is getting reloaded. But I need to reload parent component. Can somebody please guide me how to do this?
No need to Reload the page
Use ChangeDetectorRef to detect changes manually inside parent
Example:
parent.ts
import {ChangeDetectorRef} from '#angular.core';
constructor(private cdr:ChangeDetectorRef){}
ngOnInit(){
this.service.susbscribe((data)=>{
this.data=data;
//detect the change manually using
this.cdr.detectChanges();
//Checks this view and its children.
local change detection checks
})}
You need to pass an addition flag to skip location changes like this
'''
this.router.navigate(['parentComponent', id, type], {skipLocationChange: true});
'''

Angular 2 html form validation

I've created a form using html validations with Angular 2.
I want to to check the sate of the inputs (no empty, correct format, etc) when the user click to a certain button. At the moment I'm doing it as following:
<form id="memberForm" #memberForm="ngForm" >
<input
type="text"
id="MemberName"
required
name="MemberName"
[(ngModel)]="newMember.name">
</form>
<div
[ngClass]="{'button_disabledButton' : !memberForm?.valid}"
(click)="onSubmit(memberForm?.valid, memberForm);">
<span>Next</span>
</div>
With this, I'm only evaluating the input once clicked and focus out. How can I make it hapens when the user click in the "Next" element?
You should make getter/setter solution for your ngModel input.
In the .ts file in the appropriate class put this:
savedVar:string = '';
get variable(): string {
return this.savedVar;
}
set variable(str: string) {
this.savedVar = str;
// do your validation
}
In template use ngModel=variable like this:
<input [(ngModel)]="variable">

Angular, validate form when submitting from outside form [duplicate]

Given this code:
<div ng-controller="MyCtrl">
<form ng-submit="onSubmitted()">
Header inputs:
<input type="name" ng-model="sample" required/>
<input type="name" ng-model="sampleX" required/>
<input type="submit" value="This submit triggers validation. But I wanted to put this button at the end of the page"/>
</form>
<hr/>
Some other form here. Think line items
<hr />
<a class="btn" ng-click="/* what could should be put here, so this can trigger the firt form's validation, then submit? */">Wanted this submit button to trigger the validation+submit on the form in which this button doesn't belong</a>
</div>
var app = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.onSubmitted = function() {
alert('submitted!');
};
}
I want the last button to trigger the validation(then submit when things are valid) on first form. As of now, only the button inside the form can trigger that form's validation and submission. Is there any possible way for a button outside the form to do that?
Live test: http://jsfiddle.net/dzjV4/1/
You can create directive which you can then attach to <a class="btn".... Check this jsfiddle
http://jsfiddle.net/dzjV4/2/
Note that I added to <input type='submit' id='clickMe'... and linked it with link at the bottom <a class='btn' linked="clickMe"...
for (control of $scope.[form name].$$controls) {
control.$setDirty();
control.$validate();
}
You can try the above codes. Make it running before submit.
Ideally there'd be a programmatic way to cause validation to re-run across a form. I have not investigated that completely but had a situation that required multiple controls to be re-validated based on different data in the scope -- without the user interacting with the individual controls. This arose because the form had two action buttons which each required different validation rules be in play when they were clicked.
The UI requirement changed before I fully implemented forcing re-validation but before it did I got most of what I needed by copying and then re-setting the form's data. This forced re-validation across the form within the current scope. Basically, it's along the lines of the following (not tested, but taken from the code that was working). In this case the form's data was bound to the properties in one object.
var formData = $parse(<form's model>);
var dataCopy = angular.copy( formData($scope) );
formData.assign( $scope, dataCopy );
This may or may not be acceptable, but if you can get away with the SUBMIT button being disabled until the form is completed, you can do this:
<form name="formName">
<input ng-required="true" />
</form>
<button ng-click="someFunction()" ng-disabled="formName.$invalid" />
It's also worth noting that this works in IE9 (if you're worried about that).
Give your form a name:
<div ng-controller="MyCtrl">
<form name="myForm">
<input name="myInput" />
</form>
</div>
So you can access your form validation status on your scope.
app.controller('MyCtrl', function($scope) {
$scope.myForm.$valid // form valid or not
$scope.myForm.myInput // input valid or not
// do something with myForm, e.g. display a message manually
})
angular doc
There is no way to trigger browser form behavior outside of a form. You have to do this manually.
Since my form fields only show validation messages if a field is invalid, and has been touched by the user:
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}