How to reset the ng-multiselect-dropdown - html

I want to reset the ng-multiselect-dropdown. Is it necessary to put it in a form ?
code -
app.component.html
<div>
<p id = "node">Select a Root API Object - </p>
<p style="width:50%">
<ng-multiselect-dropdown [placeholder]="'Select Root API Object'" [data]="dropdownListRoot" [(ngModel)]="selectedItemsRoot" [settings]="dropdownSettingsRoot"
(onSelect)="onItemSelectRoot($event)" (onSelectAll)="onSelectAllRoot($event)">
</ng-multiselect-dropdown>
</p>
</div>
app.component.ts
export class HierarchySearchComponent implements OnInit {
onItemSelectRoot(item: any) {
this.onlyRootItemSelect = true; // for cypher also.
console.log(item);
this.rootItem = item;
this.nodeSelect = true;
this.rootItemText = this.rootItem.item_text;
console.log("this.rootItemText = ", this.rootItemText);
}
onSelectAllRoot(items: any) {
console.log("On Item select all" + items);
this.nodeSelect = true;
}
}

it is not necessary to put it in form.
Just make the selectedItemsRoot array empty. Call this function resetSelection() from the element/context.
if you are using the button to clear selection, it can be
.html
`<button (click)="resetSelection()" >clear</button>`
.ts
resetSelection() {
this.selectedItemsRoot = [];
}

It is not necessary to put it in a form - if you want to clear the selected items, just set the selectedItemsRoot object to an empty array. I.e.
clearSelection() {
this.selecteditemsRoot = [];
}
And bind that function to a button, or call it with any other method you are using to clear the selection.

if you are using formControlName instead of ngModel then you can use something like this
this.myForm.get(formControlName).setValue([]);

Related

How to close a modal on browser back button using react-router-dom?

I'm using react-router-dom and what I want is to be able to close a Modal when I click browser back button.
Also, in my scenario, the modal component is not the part of Switch. So how can I close the modal.
Thanks in advance. :)
You could probably use something like this to detect the press of the Back button.
componentDidUpdate() {
window.onpopstate = e => {
}
}
And then, depending on your modal (Bootstrap or something else) you can call .hide() or .close().
I've made a simple hook called useAppendLocationState that does all the job:
function SomeComponent() {
const [showModal , appendShowModal ] = useAppendLocationState('showModal');
return (
<div>
<div>...some view...</div>
<button onClick={() => appendOpenModal(true)}>open modal</button>
{showModal && <SomeModal closeHandler={() => window.history.back()} />}
</div>
)
}
useAppendLocationState returns a array with two entries just like useState, The first entry is the state prop value coming from browser location state and the second entry is a method that pushes a new item to browser history with new state prop appended to current location state.
here is our useAppendLocationState definition:
import { useHistory } from 'react-router';
export function useAppendLocationState(key) {
if (!key) throw new Error("key cannot be null or empty value")
const history = useHistory()
const currentLocationState = history.location.state;
const appendStateItemValue = (value) => {
const newLocationState = { ...currentLocationState }
newLocationState[key] = value;
history.push(history.location.pathname, newLocationState)
}
const stateItemValue = history.location.state && history.location.state[key]
return [stateItemValue, appendStateItemValue]
}
export default useAppendLocationState
Have you tried: ComponentWillUnmount?

How to make a checkbox checked dynamically after passing a value from another component in angular 6?

My second.html:
<div class="col-lg-4 col-md-4 col-sm-4">
<input type="checkbox" class="checkmark" name="nond" [checked]="r=='true'" (change)="nond($event, check)">
</div>
My second.ts:
Flag(): void {
this._call.getflag()
.subscribe(r => {
this.Flag = r;
let value = true;
if (r == value) {
let data = {
'flag': r
};
let obj = this.$modal.show(DComponent, undefined, data)
.subscribe(r => {
if (r.click === 'CONTINUE') {
obj.unsubscribe();
}
});
}
});
}
I have a checkbox in this html page. In my typescript file, on initialize, Im calling an API function & it will return a boolean value. Based on that I need to check my checkbox & should pass the checked value. So can anybody please tell me how to do this in angular 6?
If your "r" is a boolean variable then you don't even need to use [checked]
don't need below
[checked]="r=='true'" (change)="nond($event, check)"
Instead do like this
<button (click)="changeCheckBoxStatus(true)">Check</button>
<button (click)="changeCheckBoxStatus(false)">Uncheck</button>
<input type="checkbox" class="checkmark" name="nond" [ngModel]="checkboxStatus" (ngModelChange)="checkBoxStatus($event)"> checkBox
component
export class CheckBoxComponent {
checkboxStatus = true;
checkBoxStatus(event) {
console.log(event);
this.checkboxStatus = event;
}
changeCheckBoxStatus(status: boolean) {
this.checkboxStatus = status;
}
}
Note:
If you use (change) event, it will trigger only when user physically clicks the checkbox and it won't trigger when you update checkbox status from you component

Scope value not updating in view in IONIC 1 and Angular js

I have a requirement like saving two previous login details.
I am done with it. But my view will update only on refresh.But scope values are updated.
Tried with scope.apply,digest,timeout. But nothing seems to work here.
$scope.loginUserName=localStorage.getItem("loginUserName");
$scope.userName=localStorage.getItem("userName");
$scope.mobileNumber=localStorage.getItem("mobileNumber");
$scope.loginData = {};
$scope.userLogin = function(loginData) {
userService.userLogin(loginData).then(function(success) {
var res=success.message;
if(res==='success'){
if(localStorage.getItem("userName1")==null || localStorage.getItem("userName1") == success.firstName){
localStorage.setItem("userName1",success.firstName);
localStorage.setItem("loginUserName",success.firstName);
}else if(localStorage.getItem("userName2")==null || localStorage.getItem("userName2") == success.firstName ){
localStorage.setItem("userName2",success.firstName);
localStorage.setItem("loginUserName",success.firstName);
}
localStorage.setItem("userName",success.firstName);
$scope.userName=success.firstName;
$scope.mobileNumber = success.mobileNumber;
$scope.loginData = {};
$state.go('app.home');
}else{
$scope.message ='Wrong pin.Try again or click Forgot password to reset it.';
}
},function(error){
});
};
$scope.loginPerson = function(mobileNumber,userName){
localStorage.setItem("loginUserName",userName);
// here userName is updating,but not reflecting in view
$scope.loginUserName=localStorage.getItem("loginUserName");
//setTimeout(function(){ $scope.$apply(); });
console.log("In loginPerson:"+userName);
$state.go('app.start');
}
start.html
<span ng-if="loginUserName !=null">
<p class="startP">Enter pin for {{loginUserName}}
<i class="icon ion-chevron-down" ui-sref="app.loginOptions">
</i></p>
</span>
State
//Here is the state details,I have same controller for two state.
.state('app.loginOptions', {
url: '/loginOptions',
views: {
'menuContent': {
templateUrl: 'templates/loginOptions.html',
controller:'LoginCtrl'
}
}
})
.state('app.start',{
url:'/start',
views:{
'menuContent':{
templateUrl:'templates/start.html',
controller:'LoginCtrl'
}
}
EDIT
I have used within object also,But nothing is changed.
step 1) please use angular copy while get data from localstorage to $scope $scope.xyz=angular.copy(localstorage.get('key'))
after implement step 1 then not work use $scope.$apply(); after set value in $scope.
try to use loginUserName as a property of an object instead a property of scope directly. Sometimes angularjs fail to update view for these values.
Like
$scope.data={
loginUserName:""
};
Then inside your function
$scope.userLogin = function(loginData) {
...
$scope.data.loginUserName=localStorage.getItem("loginUserNa‌​me");
// To check it
console.log($scope.data);
}
html
<span ng-if="data.loginUserName !=null">
...
</span>
Update
Change the loginPerson function like below.
$scope.loginPerson = function(mobileNumber,userName){
localStorage.setItem("loginUserName",userName);
$scope.data.loginUserName=localStorage.getItem("loginUserName");
console.log("In loginPerson:"+userName);
console.log($scope.data);
}

searchbox in angular 2 doesn't return the whole object

I'm very new to Angular2 and 4.
I have a list of items of type class (Item).
Items fields are name, price and description.
I want to make a searchbox when the user types the name of the item, it displays the correct item object.
I followed this example: http://www.angulartutorial.net/2017/03/simple-search-using-pipe-in-angular-2.html
but It didnt work, I think because if was searching between strings not objects of type item.
If you used the code in the tutorial, with an array of objects you just need to update the return statement of the transform method in your Angular2 Pipe like this:
return value.filter(function (el: any) {
return el.name.toLowerCase().indexOf(input) > -1;
})
PS: I added el.name but you can search through the description or whatever you like.
Create a custom pipe and pass search parameters to that pipe, something like below example
<li *ngFor="let n of list | FilterPipe: queryString : searchableList ">
{{n.name}} ({{n.age}})
</li>
this.searchableList = ['name','age']
And your custom pipe
#Pipe({
name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
transform(value: any, input: string,searchableList : any) {
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any) {
var isTrue = false;
for(var k in searchableList ){
if(el[searchableList[k]].toLowerCase().indexOf(input) > -1){
isTrue = true;
}
if(isTrue){
return el
}
}
})
}
return value;
}
}

Typeahead each time user writes a certain word

I'm using the ui-bootstrap typeahead for when a user types to show all the variables available for him to write which are proprieties from an object which is loaded Ex: item.cost+item.quantity.
My question is I want the suggestions only to appear each time user types "item.", I've notice the typeahead only works for one word and at the beginning.
html
<div class="modal-body">
Add expression:
<textarea style="width: 568px;" ng-model="item.formula"
uib-typeahead="state for state in states "
typeahead-show-hint="true"
typeahead-on-select="item"
ng-change="eval(item.formula)">
</textarea>
<p><b>Result:</b> <br>
<div style="width: 100%">{{ans}}
</div>
</p>
</div>
controller
ctrl.controller('myController', ['$scope', function ($scope) {
$scope.imageShowModal = function (item) { //loads the object items
$scope.item = item;
$scope.states =Object.keys(item); //get the JSON keys from item object like cost,price,quantity,workflow...
};
$scope.eval = function (v) {
try {
$scope.ans = $scope.$eval(v);
} catch (e) {
}
};
You can use a custom filter in your uib-typeahead expression, ex: uib-typeahead="state for state in states | myCustomFilter:$viewValue"
A custom filter in your case might look like this:
angular.module('myApp')
.filter('myCustomFilter', function() {
return function(list, term) {
if (term.indexOf('item.') === -1)
return [];
var filteredList = [];
angular.forEach(list, function(value) {
if (value.indexOf(term) !== -1)
filteredList.push(value);
});
return filteredList;
}
});
See also: AngularJs UI typeahead match on leading characters