Angular: Select checkbox on another checkbox selection ( dynamic form control ) - javascript

I'm new to angular.
I have this UI. I wanted to make Bill To checkbox checked if any one (Address, Email or Phone) of the checkbox is checked. I'm using dynamic form control for checkbox.
code snippet: This solution didnt work , as combineLatest is emitting only when all the three checkboxes get selected
combineLatest([this.form.customerInfo.address.valueChanges(),
this.form.customerInfo.email.valueChanges(),
this.form.customerInfo.phone.valueChanges()])
.subscribe((formValues)=>{
if (formValues.every((value) => value === false || value === undefined)) {
this.form.customerInfo.billTo.setValue(false)
}
else {
this.form.customerInfo.billTo.setValue(true)
}
});
this.form.customerInfo.billTo.valueChanges().pipe(distinctUntilChanged()).subscribe(value =>{
// if billTo is false or unchecked- unchecked all
if(!value){
this.form.customerInfo.address.setValue(value);
this.form.customerInfo.phone.setValue(value);
this.form.customerInfo.email.setValue(value);
}
})
another solution: it's a bit complicated
combineLatest([
this.form.customer.address.valueChanges().pipe(startWith(false)),
this.form.customer.phone.valueChanges().pipe(startWith(false)),
this.form.customer.email.valueChanges().pipe(startWith(false)),
])
// adding debounce until we can listen for form changes and patch multiple form values simultaneously
.pipe(debounceTime(100))
.subscribe(([address, phone, email]) => {
if ((address || phone || email) && !this.form.customerInfo.billTo.value) {
// one of the nested values is true, and billTo is false, make billTo true
this.form.customer.billTo.setValue(true);
}
});
// when customer toggle billTo to false, we set all children to false
this.form.customer.billTo
.valueChanges()
.pipe(filter((value) => value !== true))
.subscribe(() => {
const address = this.form.customer.address.value;
const phone = this.form.customer.phone.value;
const email = this.form.customer.email.value;
// if any of the nested values are true, set them to false
if (address) {
this.form.customer.address.setValue(false);
}
if (phone) {
this.form.customer.phone.setValue(false);
}
if (email) {
this.form.customer.email.setValue(false);
}
});
Can anyone tell how to improve this? Thanks in advance.

Related

p-multiSelect how prevent adding elements with the same index

I have a list of options for multi-select. in one of the option I should add another field-remark field. so selecting in the first time add this field. but when removing the selection it does not removing this selection from the array becouse I did not remove the remark field. so when select this option again will add twice the same index(one with the remark field and one with null in the remark) I need to set value only if I dont have this index in the array
<p-multiSelect [required]="formGroup.hasError('remark-reasons-required')"
[options]="reasons" defaultLabel="" formControlName="remarks" optionLabel="hebName"
selectedItemsLabel="{0} "
(onChange)="onChangeReasonsValue($event)"></p-multiSelect>
onChangeReasonsValue(event: { value: ReviewDecisionReasonModel[] }): void {
//
var selectedArray = event.value.filter(function (item, pos) {
return event.value.indexOf(item) == pos;
})
this.formGroup.get('remarks').setValue(selectedArray);
this.selectedReasons = selectedArray;
this._decision.reasons = selectedArray;
}
It seems the multi-select component have a bug, where the disabled/removed options from the component remain added to the related formControl.
I propose you add a "disabled" property to your options, and set this option as the selections change instead of adding/removing them. After that, you could adjust the formValues with only enabled options.
Also, you could not use (OnChange) in favor of subscribing to the form changes from the component.
something like
otherReasonWhen2 = { id: 3, hebName: 'heb3', freeTextAllow: false, disabled: true };
reasons = [
{ id: 1, hebName: 'heb1', freeTextAllow: false, disabled: false },
{ id: 2, hebName: 'heb2', freeTextAllow: false, disabled: false },
this.otherReasonWhen2,
];
ngOnInit() {
this.formGroup.get('remarks').valueChanges.subscribe((newValues) => {
console.log(newValues) // This is here for you to see the values as they change
this.otherReasonWhen2.disabled = newValues.every(reason => reason.id !== 2)
if (newValues.some(reason => reason.disabled)){
// work-around for the observed bug: when there are disabled options selected, remove them from the form.
this.formGroup.get('remarks').setValue(newValues.filter(reason => !reason.disabled));
}
});
}
and don't forget to add the directive to disabled the option:
<p-multiSelect
[options]="reasons"
optionDisabled="disabled" <-- Here
defaultLabel=""
formControlName="remarks"
optionLabel="hebName"
selectedItemsLabel="{0} "
></p-multiSelect>

Not able to perform 2 actions on the same component when hardware back button is pressed in react-native,below are the code regarding the backhandler

backAction = () => {
if (this.props.navigation.isFocused() && !this.state.otpScreen) {
this.setState({ showLoginScreen: true });
return true;
} else if(this.state.showLoginScreen) {
this.props.navigation.dispatch(CommonActions.reset({
index: 0,
routes: [
{ name: 'Login' },
],
}))
return false;
}
};
the code above is for action that should be done by the hardware back press, at first it should show the one screen and on the second press it should exit the app, both otp screen and login screen are on the same component, I'm just hiding based on the condition ...
at the first time it is working as per the condition but for the second time it's not.
componentDidMount() {
this.focusListener = this.props.navigation.addListener('focus', () => {
this.setState({
mobile: '',
showLoginScreen: true,
});
});
this.getDataFromStorage();
AsyncStorage.setItem('countryCode', '+91');
BackHandler.addEventListener(
"hardwareBackPress",
this.backAction
);
}
componentWillUnmount() {
clearInterval(this.interval)
BackHandler.addEventListener('hardwareBackPress', () => { return false })
}
can anyone pls help me how to do this,thanks in Advance
I guess your problem is that you can't access the 'current' value of a state inside a listener.
More Details here
Try to use a Reference instead of a state

Is it possible to create a search function with a v-select alongside user input with vuejs

What I am trying to achieve is that,when the user types in the search bar what they are looking for( for example if they want an account that starts with SAE), when the user clicks on the dropdown and selects one of the items(for example, Account), it should bring back a result with all the records that have the account of SAE.I have tried to implement an #change event from the v-select and it does recognize that I am selecting one of the items in the dropdown. I am not sure if it is possible because I have translated the items in the dropdown using Vuei18n.
The code below is for the search bar and dropdown list
<v-text-field
v-model="searchField"
:label="$t('searchPage.search')"
placeholder="..."
clearable
clear-icon="mdi-close-circle-outline"
class="mr-4"
#keyup.enter="loader = 'loading'"
/>
<v-select
v-show="standardSearch"
:label="$t('searchPage.searchBy')"
:items="selection"
chips
small-chips
deletable-chips
#change="searchByDropdown"
/>
//The code that is in the js file
data(){
const t = this.$t.bind(this);
return {
searchField:""
searchSelection:[
t("searchPage.meterNumber"),
t("searchPage.account"),
t("searchPage.billingArea")
]
}
}
And the below code is for the searchByDropdown event
searchByDropdown(e) {
const t = this.$t.bind(this);
var searchInput = `${this.searchField}`;
var searchSelection = `${this.selection}`;
debugger;
// t("searchPage.meterNumber"),
// t("searchPage.account"),
// t("searchPage.billingArea")
switch (e) {
case searchInput && e == t("searchPage.meterNumber"):
//After this I want to start searching
debugger;
break;
case searchInput && e == t("searchPage.account"):
break;
case searchInput && e == t("searchPage.billingArea"):
break;
default:
searchSelection == null;
}
console.log(e + searchInput);
}
The search results will be displayed in a treeview, but I would want to know if this achievable
vuetify has its own built-in component named "v-autocomplete". its exactly like v-select and a searchbar at the top enabling user to search through Items to find the most closest item to the searched text.
I have figured out how to solve this. All i needed was a variable that stores the value of the dropdown and if that value matches the dropdowns value then I can use it to search for the data
//This is the dropdown search function
//The search key is a variable that will store the value of the dropdown hence 'e'
selection: [
{
name: t("searchPage.meterNumber"),
value: "meterNumber"
},
{
name: t("searchPage.account"),
value: "account"
},
{
name: t("searchPage.billingArea"),
value: "billingArea"
}
],
searchByDropdown(e) {
debugger;
this.searchKey = e;
console.log(e);
},
if (searchInput != "" && this.searchKey == "meterNumber") {
this.$services.accountService
.accountSearchMultiple({
organisationID: 0,
meterNumber: searchInput,
n: 100
})
.then(response => {
this.treeData = response.data.treeItems;
this.itemData = response.data.dataItems;
this.revealTree = false;
this.snackbar = {
message: "Your search is successful",
color: "success",
show: true
};
})
.catch(() => {
this.revealTree = true;
this.snackbar = {
message: "Invalid Search",
color: "error",
show: true
};
});
}

React-table on click single row highlight. Disable multiple select

I am working on small function add, edit, delete function in React-table.
my codes are running.
My issue if the user clicks on the row it gets selected at the same time if you click on another row its get selected but it doesn't disable the previously selected row. Basically, the user can select one row at the time. Disable multiple select.
Also, it would be great if anyone can review my add, update, delete function. Whether it is right approach or not.
Running Code
Fixed
getTrProps={(state, rowInfo) => {
if (rowInfo && rowInfo.row) {
return {
onClick: e => {
console.log("inside");
if (rowInfo.index != this.state.rowEdit) {
this.setState({
rowEdit: rowInfo.index,
selectedRowIndex: rowInfo.original,
selectionChanged: this.state.selectionChanged
? false
: true
});
} else {
this.setState({
rowEdit: null
});
}
console.log(rowInfo.index);
console.log(this.state.rowEdit);
},
style: {
background:
rowInfo.index === this.state.rowEdit ? "#00afec" : "white",
color:
rowInfo.index === this.state.rowEdit ? "white" : "black"
}
};
} else {
return {};
}
}}

such empty alert with jsx / react alternatives

So I was thinking I found a great way to alert users that the array is empty and there's nothing to display but actually my technique is not well implemented and only works onFocus or page reload, I put the function on componentDidMount()
componentDidMount = () => {
this.setState({loading: true})
const { currentUser } = fire.auth();
fire.database().ref(`/master/${currentUser.uid}/feed/sponsors/`)
this.setState({
sponsorsList:sponsorsList,
}, () => {
if (this.state.sponsorsList.length === 0)
this.setState({loading: false, empty: true})
});
});
}
This works but such empty text in the view still appears after I push something to the array, how do I trigger that .length function ?
{this.state.empty ? <h6 class='mb-3'>Such empty!</h6> : null }
Please someone suggest a better alternative.
I think you need to add else logic:
if (this.state.sponsorsList.length === 0) {
this.setState({ loading: false, empty: true })
} else { // Here are the additions
this.setState({ loading: false, empty: false })
}
Oh, then you can write:
{this.state.empty && <h6 class="mb-3">Such empty!</h6>}
Hope it helps :)

Categories

Resources