how to get the name and value of the checked checkbox of child component from parent component in vue js? - vuejs3

Child Component
<template>
<ul>
<li class="dropdown">
<div>
<label class="form-control" ref="checkValue" v-for="(item, index) in list" :key="index">
<input type="checkbox" ref="checkUpdatedBox" :name="item.name" :value="item.name" #click="selectedFilteredArray(item)" />
{{ item.name }}
</label>
</div>
</li>
</ul>
</template>
Here I want the name(item.name) or value(item.name) of the checkbox from the child component. As the input box is rendered dynamically with for loop.
Parent Component
<template>
<ChildComponent ref="checkboxes"/>
</template>
<script>
import SideBar from '../layouts/SideBar.vue'
export default {
methods: {
updateFunction() {
const unCheckBoxes = this.$refs.checkboxes.$refs.checkUpdatedBox
const unCheckBoxes1 = this.$refs.checkboxes.$refs.checkValue
console.log('unCheckBoxes1 ', unCheckBoxes1.innerText)
console.log(unCheckBoxes.checked) // true
}
}
}
</script>
In parent component, I'm trying to access name and value of the checkbox with the help of $refs and yes I'm trying to get name and value of the checkbox from a function. I'm only getting to know that whether the checkbox is checked or not.
But i want to know that checked checkbox value(item.name) or name(item.name).
is there something I'm missing out?
or
Is there any other method to get the name or value?

You can slimily use JavaScript to get value of selected checkbox.
var checkedValue = [];
var inputElements = document.getElementsByClassName('checkbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue.push({value:inputElements[i].value,name:inputElements[i].name});
}
}
console.log(checkedValue);

Related

How to retrieve the elements from Shadow DOM and pass property?

With the help of Lit library we have implemented the component that should render the list with items, where each item is rendered with a separate component:
<div>
<slot name="label"> Here goes the title </slot>
<slot name="list"></slot>
</div>
We pass data to the component like following:
<webc-list ?divided=${true}>
<span slot="label">Title</span>
<ul slot="list">
${items.map(
item =>
html`<webc-list-item
>${item}</webc-list-item
>`,
)}
</ul>
</webc-list>
My question is how can I pass the divided property to the <webc-list-item>.
I tried to access the elements
firstUpdated() {
const dividedProperty = this.divided;
this.renderRoot.querySelector('slot[name=list]')?.assignedElements({ flatten: true })
?.forEach(el => {
if (el && el.tagName && el.tagName.toLowerCase().includes('webc-list-item')) {
el.setAttribute('divided', `${dividedProperty}`);
}
});
But it doesn't work like this, any help would be appreciated!

Data Binding between parent and child component in vue3 composition api

I have successfully bound data in a two way format in vue 3 like this :
<template>
<p for="">Year of Incorporation</p>
<input type="text" v-model="input" />
<div>
{{ input }}
</div>
</template>
<script>
export default {
setup() {
let input = ref("")
return {input};
},
};
</script>
What I want to do now is put the input inside a child component like this:
Parent Component:
<template>
<Child v-model="input" />
{{input}}
</template>
Child Component:
<template>
<input type="text" v-model="babyInput" />
</template>
<script>
export default {
setup() {
let babyInput = ref("")
return {babyInput};
},
};
</script>
The Vue.js documentation presents a nice way of handling v-model-directives with custom components:
Bind the value to the child component
Emit an event when the Child's input changes
You can see this example from the docs with the composition when you toggle the switch in the right-top corner (at https://vuejs.org/guide/components/events.html#usage-with-v-model).

vue3 Cannot loop over an array of object passed as prop

In vue3 I am passing an array of options from parent component to child component in order to use it as options for a select.
At the moment, I am not able to use it to initialize my select.
Here is the child component SmartNumberInput
<template>
<div>
<div>Selected: {{ selected }} Initial:{{ initial }}</div>
{{ options }}
<div v-for="option in options" :key="option.value">
{{ option.text }}
</div>
<input type="number" v-model="input_value" />
<select v-model="selected">
<option
v-for="option in options"
:value="option.value"
:key="option.value"
>
{{ option.text }}
</option>
</select>
</div>
</template>
<script>
export default {
props: ["initial", "options"],
data() {
return {
selected: "",
input_value: "",
};
},
};
</script>
Here is the parent component
<template>
<div>
<h1>Hi! I am the root component</h1>
<div class="smart-number-input">
<smart-number-input
initial="B"
options="[{text:'Liters',value:'A'},{text:'Gallons',value:'B'},{text:'Pints',value:'C'}]"
/>
</div>
</div>
</template>
<script>
import SmartNumberInput from "./SmartNumberInput.vue";
export default {
data() {
return {
initial: "salut",
};
},
components: { SmartNumberInput },
};
</script>
<style>
.smart-number-input {
width: 100%;
background:#EEE;
}
</style>
In the result I get (see picture) there is no option visible in the select though when the small arrow is clicked it expands with a long empty list.
The {{options}} statement in the child displays what I pass as prop i.e. an array of objects but nothing is displayed in the div where I use a v-for loop.
When I declare the options as data in the child both loops (div and select) work fine.
Could somebody explain what is wrong in the way I pass or use the array of options ?
change options to :options (add colon symbol)
.
if you not put colon, it will treat the value as a String...

Angular 6 - change checkbox style whether is checked

I have a list of checkbox and I want to underline the one that is checked. My code looks like the following:
TS file:
currentQuarter: string;
quarters: Observable<MeseRiferimento[]>;
q1: MeseRiferimento = new MeseRiferimento();
q2: MeseRiferimento = new MeseRiferimento();
ngOnInit() {
q1.desc = "One";
q1.id = "1";
q2.desc = "Two";
q2.id = "2"
currentQuarter = q1.id;
quarters.of([q1, q2]);
}
isQuarterSelected(q: MeseRiferimento): boolean {
return this.currentQuarter === this.getKeyFromQuarter(q);
}
HTML file:
<div *ngFor="let q of quarters | async" class="col-1 my-auto m-stati">
<label class="custom-control custom-checkbox ra-check">
<input type="checkbox" class="custom-control-input" [ngClass]="{'checked': isQuarterSelected(q) }">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">{{q.descrizione}}</span>
</label>
</div>
CSS file:
.custom-control-input:checked~.custom-control-indicator {
color: #fff;
background-color: #3bb8eb;
}
These are the issue with this code:
1. when I load the page, the default checked checkbox has correctly the class 'checked' but the CSS is not applied, i.e. it's not underlined
2. when I manually select a checkbox the class 'checked' correctly applies and the CSS too applies
3. when I manually select another checkbox, the class 'checked' correctly switches from one to the other, but the CSS of the former do not update, i.e. the previous checkbox remains underlined
Thanks for any advice.
.custom-control-input:checked~.custom-control-indicator
:checked doesn't mean that it has the checked class, but it means that it's actually checked. If you want to select the checked class, use a dot in place of a colon:
.custom-control-input.checked~.custom-control-indicator

Angular 7: patching value of radio button Form Control does not update UI

I am using a HTML template in Angular 7 that consists of a number of radio buttons, each with an associated label - this is associated with a FormGroup object. Clicking on the label should change the state of the radio button to be selected and update the value of the associated FormControl. This works, the problem I have is setting a particular radio button to be selected when the UI loads, or using patchValue - the state of the formGroup is correct when the template is loaded, but the UI does not reflect that a particular radioButton has been selected.
Here's code that shows the problem:
export class AppComponent {
frequencyMinutesOptions: number[] = [1, 2, 5, 10, 60];
myForm: FormGroup;
constructor() {
}
ngOnInit() {
this.myForm = new FormGroup({
frequencyMinutes: new FormControl(5,[])
});
this.myForm.patchValue({'frequencyMinutes':10})
}
}
The HTML template:
<form [formGroup]="myForm">
<ul>
<li *ngFor="let frequency of frequencyMinutesOptions">
<input id="asset-frequency-{{frequency}}" type="radio" value={{frequency}} formControlName="frequencyMinutes" />
<label for="asset-frequency-{{frequency}}"> {{frequency}} </label>
</li>
</ul>
</form>
Relevant CSS:
input {
display: none;
}
input:checked+label {
background-color: blue;
color: #ffffff;
}
You may see a working demo of this here:
https://stackblitz.com/edit/angular-of2ubt
(I know that I'm supposed to embed code examples within the Stackoverflow editor but I'm not sure how to do this with Angular 7 / typescript or if its even possible)
it's a type error. In your html form, the value="10" is interpreted as the string '10'.
You have to use
this.myForm.patchValue({'frequencyMinutes':'10'}) or (see [value])
<input id="asset-frequency-{{frequency}}" type="radio" [value]="frequency" formControlName="frequencyMinutes" />
Either use formGroupName or call external function to make default radio button as true.
<div class="container">
<form [formGroup]="myForm">
<ul>
<li *ngFor="let frequency of frequencyMinutesOptions">
<input id="asset-frequency-{{frequency}}" type="radio" value="{{frequency}}" formControlName="frequencyMinutes" [checked]="isDefaultSelection(frequency)" >
<label for="asset-frequency-{{frequency}}"> {{frequency}} </label>
</li>
</ul>
</form>
<div class="debug">{{myForm.value | json}}
</div>
</div>
export class AppComponent {
frequencyMinutesOptions: number[] = [1, 2, 5, 10, 60];
myForm: FormGroup;
constructor() {
}
ngOnInit() {
this.myForm = new FormGroup({
frequencyMinutes: new FormControl(5,[])
});
this.myForm.patchValue({'frequencyMinutes':10})
}
isDefaultSelection(frequency) {
return frequency == 10 ? true : false;
}
}
or simply use property-binding
<input id="asset-frequency-{{frequency}}" type="radio" [value]="frequency" formControlName="frequencyMinutes">

Resources