Add a checked attribute to a dynamic radio button - html

I'm building a *ngFor dynamic radio button. I need to add some kind of attribute that can be used to determine if the button is active or not. This is not for the purpose of functionality, the selection builds the property on my reactive form fine. The purpose is to satisfy testing.
<label *ngFor="let order of orders">
<input formControlName="orders" type="radio" name="orders" [value]="order.id" />
{{order.name}}
</label>
I've tried adding a checked attribute but this just adds the attribute to all radios. I thought angular provided a ngChecked property, but I think that was for AngularJS.
Any solution to determine/show that the selected radio is active would be a solution.
https://stackblitz.com/edit/angular-t2gd4g

simply by get the value of the form control orders you will be applied to know the selected one or in case of apply a spesifect design you can add a checked class for the selected one
<label *ngFor="let order of orders"
[ngClass]="{'checked':form.get('orders').value == order.id}">
<input formControlName="orders" type="radio" name="orders" [value]="order.id" />
{{order.name}}
</label>
another way to get the selected order by create a property
get selectedOrder() {
const selected =this.form.get('orders').value;
if (selected) {
return this.orders.find(o => o.id == selected )
} else {
return null
}
}
demo 🚀

In your .ts file declare changeHandler() function like this :
changeHandler(index){
console.log(`radio-button ${index+1} is active`);
}
In your .html file, in your *ngFor declare index which can be used to find the current state of checkbox. So the following demo shows which checkbox is active :
<label *ngFor="let order of orders; let i = index;">
<input formControlName="orders" type="radio" name="orders" [value]="order.id" (ngModelChange)="changeHandler(i)"/>
{{order.name}}
</label>
Demo : enter link description here
Note : see console to see active button

Related

How to switch between to value from switch input?

I have this input button: image
The code of input:
<div class="media">
<label class="col-form-label m-r-10">Status Of System</label>
<div class="media-body text-right icon-state">
<label class="switch">
<input
type="checkbox"
name="status"
value="{{ setting()->status == '1' ? 0 : 1 }}"
>
<span class="switch-state bg-primary"></span>
</label>
the setting()->status is helper function:
if (! function_exists('setting') ) {
function setting(){
return \App\Setting::first();
}
}
And in the column(status), the default is 1.
The problem is when I try to switch between 1 and 0. Notice value attribute in input I try to say if the column in database 1 put 0 else put 1 to switch the value, but this way does not run find! How can do something like this :(
If I correctly understand your question, try like that:
Check checkbox according setting value:
<input
type="checkbox"
name="status"
#if(1 === setting()->status) checked #endif
>
Here you retrieved status from database. If it exists and exactly equals 1, checkbox will be checked. If not - unchecked.
Next you want to change database value according this checkbox checked state.
Checkbox field appears in $request only if checkbox checked. So, try to refactor a bit your controller:
$setting = \App\Setting::first(); // your setting
$setting->status = isset($request->status) ? 1 : 0; // if status exists in request, it means that checkbox was checked
$setting->save(); // update your database row
The problem is just one:
when a checkbox isn't checked, it's value isn't inserted in the request. So you have to check before the update if that checkbox value exist.
So instead of
setting()->update($request->all());
you have to do
$params = $request->all();
if(!isset($params['status'])) $params['status'] = 1;
setting()->update($params);
Also on the internet there is another solution, which is to add a hidden input with the same name and with the value that you want if that checkbox isn't checked like this:
<input type="hidden" name="status" value="1">
But in my opinion, it's just a dirty workaround... but you can have a try

change style using ngModelChange

I was wondering if it was possible to style an element using ngModelChange. I tried the following but that doesn't work
<input class="input" [(ngModel)]="counter" (ngModelChange)="$event > 2 ? [style.border-color]='#ff4d4d' : [style.border-color]='#dbdbdb'" type="number">
I know that I could do something like
<input class="input" [(ngModel)]="counter" (ngModelChange)="$event > 2 ? error=true : error=false" type="number" [style.border-color]="error ? '#ff4d4d' : '#dbdbdb'">
But I want to remove if possible the 'error' attribute and assign directly the style to the input depending of the condition
Instead of handling ngModelChange, you could use normal style binding with the condition on counter, which has the same value as the $event parameter of ngModelChange:
<input [(ngModel)]="counter" [style.border-color]="counter > 2 ? '#ff4d4d' : '#dbdbdb'" class="input" type="number">
See this stackblitz for a demo.
I don't think that will be possible as we can't do property binding [style] inside an event binding (ngModelChange) as one is happening at the view and another at Model.
You can clean your code by adding function based approach.
HTML
<input class="input" [(ngModel)]="counter" (ngModelChange)="changeColor($event)" type="number" [style.border-color]="color" type="number">
.TS
color="dbdbdb";
changeColor(event) {
if(event > 2){
this.color = "#ff4d4d";
}else{
this.color = "#dbdbdb";
}
}

Hide 'Zero' value in input using typescript and Angular 2

<input type="text" class="form-control"
id="transactionAmount"
maxlength="10"
OnlyNumber="true"
[(ngModel)]="userBalance.transactionAmount"
name="transactionAmount"
placeholder="Amount"
required
#transactionAmount="ngModel">
Here I have to hide zero amount while user entering the values.
If he enters all zero's then only we have to hide not in cases like 20,30,100 etc...
I'm using Angular 2.
<input type="text" class="form-control"
id="transactionAmount"
maxlength="10"
OnlyNumber="true"
[(ngModel)]="userBalance.transactionAmount"
name="transactionAmount"
placeholder="Amount"
required
#transactionAmount="ngModel"
(keyup)="hideZero()>
Added This keyUp event in Html and in .ts added below code
hideZero(){
if(this.userBalance.transactionAmount === '0' ){
this.userBalance.transactionAmount = '';
}
}
Working Absolutely fine
/* In your ts */
validateNumber(value: String) {
userBalance.transactionAmount = value && value.replace(/(?:0*)(\d*)/g, (_,value1) => {
return value1;
})
}
<input (input)="validateNumber($event)">
Try using (ngModelChange) event which will trigger when user types values. By using regex, you can remove the last zero value and update the DOM. Hope this helps.
Angular 0 value don't display
<span *ngIf="!pro.model === '0'">{{ pro.model }}</span>
Like this,
When model value is zero that time don't display model value.
If model value is not zero that time show model value in your html pages.

Focus Label when Input is focussed with angular

I have a webpage which uses radio button labels as buttons, with inputs hidden
<li ng-repeat="amount in amounts | orderBy: amount" ng-mouseenter="$parent.hoverPrompt = $parent.amounts[$index].donationPrompt" ng-mouseleave="$parent.hoverPrompt = null">
<input type="radio" name="amount_{{amount.suggestedAmount}}" id="donate_{{amount.suggestedAmount}}" ng-value="{{amount.suggestedAmount}}" ng-model="donate.amount" string-to-number />
<label class="as-button" for="donate_{{amount.suggestedAmount}}">${{amount.suggestedAmount}}</label>
</li>
I want my labels to be visibly highlighted when they or their associated hidden inputs are tabbed over.
I found a ready jquery snippet but would prefer to do it in angular.
I found a CSS only solution, since in my case the label comes after the input:
.amounts input:focus + label {box-shadow: 0 0 2px $brand-primary;}
<ul class="list-group amounts">
<li ng-repeat="amount in amounts | orderBy: amount" ng-mouseenter="$parent.hoverPrompt = $parent.amounts[$index].donationPrompt" ng-mouseleave="$parent.hoverPrompt = null">
<input type="radio" name="amount_{{amount.suggestedAmount}}" id="donate_{{amount.suggestedAmount}}" ng-value="{{amount.suggestedAmount}}" ng-model="donate.amount" string-to-number ng-focus="$parent.hoverPrompt = $parent.amounts[$index].donationPrompt" ng-blur="$parent.hoverPrompt = null"/>
<label class="as-button" for="donate_{{amount.suggestedAmount}}">${{amount.suggestedAmount}}</label>
</li>
Here is a plunkr that uses ng-focus to apply highlighting to the label when an associated input is focused. ng-blur is used to remove the styling when an element loses focus.
I am simply setting a scope variable called 'highlight' to true when the element is focused, and to false when the element loses focus (blur).
Ng-class is used to conditionally apply css based on my 'highlight' variable.
HTML
<div ng-repeat="data in posts">
<label ng-class="highlight == true ? 'highlight' : '' ">{{data.name}}</label>
<input type="radio" ng-focus="highlight = true" ng-blur="highlight =false" ng-class="highlight == true ? 'highlight' : '' " />
</div>
CSS
.highlight { background-color: yellow;}
ng-focus will not; however, work on a label element. It is limited to inputs.
In label you can use
<label class="as-button" ng-class="{'active': donate.amount == amount.suggestedAmount}"for="donate_{{amount.suggestedAmount}}">${{amount.suggestedAmount}}</label>
Using ng-class="{'active': boolean} is consistent work on old and new angularjs versions because it base on html class, and also it not stealing focus from another element in your page or lose focus effect if use use tab or click another one. Also I recommend using button group for for those radio button like:
<div class="btn-group" data-toogle="buttons-checkbox">
<label ng-repeat="type in petTypes" class="btn btn-primary" ng-class="{'active': pet.type==type}" ng-click="setPetType(pet,type)">
<input type="radio" name="{{pet.id}}" value="{{type}}" class="sr-only" ng-checked="pet.type==type" required>{{type}}
</label>
</div>
This from my code for my pet control app and it generate new pet when clicking a button, this part is about radio button and it work just fine. Another note is the name is what control which group the input belong to.

In AngularJS How to toggle between 2 checkboxes and get only 1 value

In AngularJS; How do I toggle between two checkboxes and get only one value
<td >
<input type="checkbox" value="{{person.person_ID}}">{{person.home_address}}
</td>
<td >
<input type="checkbox" value="{{person.person_ID}}">{{person.office_address}}
</td>
According to the requirement I have list of persons in that every person has two
columns home_address and office_address, I want to toggle between addresses and get only 1
value like if person.home_address is checked than office_address should be unchecked and vice versa, and I want to get only 1 address like "person.person_ID":home_address
You can use ng-model to bind to a value in your person instance using the following html. (A fiddle is available)
<input type="checkbox"
ng-model="person.option"
value="{{person.person_ID}}"
ng-true-value="'home'"
ng-false-value="'none'">{{person.home_address}}
<input type="checkbox"
ng-model="person.option"
value="{{person.person_ID}}"
ng-true-value="'office'"
ng-false-value="'none'">{{person.office_address}}
here the checkboxes binds to the same variable person.option which is set depending on the value of the checkbox to the expression in ng-true-value and ng-false-value. By setting these to the some value other than that of the other we can either select none, or only one.
In your controller you can simply check person.option to get what checkbox is selected.
if (person.option === 'home') { }
else if (person.option === 'office') { }