Toggle md-button class on click event - html

I want to use button as a selector, i have a toggle function on click event to get the value from the button click, now what i want to do is to show the user that the button is selected. That is i want to toggle class between md-primary and md-warn.
This is my button
<md-button class="md-fab" ng-click="getTime(0);"
value="0" aria-label="midnight" ng-class="{'active':
variable,'disable': !variable}">0</md-button>
This is the controller part
$scope.getTime = function (value) {
$scope.variable = !$scope.variable;
if($scope.variable){
console.log(value);
}
};

update ng-class like below:
<md-button class="md-fab" ng-click="getTime(0);"
value="0" aria-label="midnight" ng-class="{'md-primary':
variable,'md-warn': !variable}">0</md-button>
also make sure to add ngMaterial to your app module dependencies
here is working Plunkr hope it make it more clear for you.

Related

Space keypress on an HTML Label interpreted as checkbox click

When I add 'click' event handler on an HTML checkbox with a label, then space keypress on the label causes the checkbox's click event handler to be executed. I would like to prevent that. (The checkbox itself is hidden / not visible - this is done in some version of Bootstrap framework used in my code).
HTML:
<body>
<label for="checkbox" id="label">Click on me, I am Label for <strong>hidden</strong> Checkbox</label>
<!-- checkbox is not visible -->
<input type="checkbox" id="checkbox" style="opacity: 0" />
<!-- to be filled by JavaScript code -->
<div id="checkboxValue"></div>
</body>
JavaScript code:
import { fromEvent } from 'rxjs';
const checkbox: HTMLInputElement = document.querySelector('#checkbox');
const checkboxValue: HTMLDivElement = document.querySelector('#checkboxValue');
function updateCheckbox() {
checkboxValue.innerHTML = `Checkbox ${
checkbox.checked ? '✔️ (checked)' : '❌ (unchecked)'
}`;
}
// event handler for the checkbox being executed also for Space keypress:
fromEvent(checkbox, 'click').subscribe((event) => {
console.log('checkbox CLICK -------')
updateCheckbox();
});
updateCheckbox();
Open the Stackblitz console, click the Click on me, I am Label for hidden Checkbox.
Then press the space key and see the click handler being executed.
Demo on Stackblitz.
If a label has keyboard focus, pressing the Space key also raises the Click event.
If you want to remove focus, you can add a blur event (on the label) to remove focus so spacebar won't function to click the button :
e.target.blur();

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});
'''

Performing Click on an ElementRef object in Angular 4 [duplicate]

I am trying to fire click event (or any other event) on element programatically , In other word I want to know the similar features as offered by jQuery .trigger() method in angular2.
Is there any built in method to do this? ..... if not please suggest how can i do this
Consider the following code fragment
<form [ngFormModel]="imgUploadFrm"
(ngSubmit)="onSubmit(imgUploadFrm)">
<br>
<div class="input-field">
<input type="file" id="imgFile" (click)="onChange($event)" >
</div>
<button id="btnAdd" type="submit" (click)="showImageBrowseDlg()" )>Add Picture</button>
</form>
Here when user click the btnAdd it should fire the click event on imgFile
Angular4
Instead of
this.renderer.invokeElementMethod(
this.fileInput.nativeElement, 'dispatchEvent', [event]);
use
this.fileInput.nativeElement.dispatchEvent(event);
because invokeElementMethod won't be part of the renderer anymore.
Angular2
Use ViewChild with a template variable to get a reference to the file input, then use the Renderer to invoke dispatchEvent to fire the event:
import { Component, Renderer, ElementRef, ViewChild } from '#angular/core';
#Component({
...
template: `
...
<input #fileInput type="file" id="imgFile" (click)="onChange($event)" >
...`
})
class MyComponent {
#ViewChild('fileInput') fileInput:ElementRef;
constructor(private renderer:Renderer) {}
showImageBrowseDlg() {
// from http://stackoverflow.com/a/32010791/217408
let event = new MouseEvent('click', {bubbles: true});
this.renderer.invokeElementMethod(
this.fileInput.nativeElement, 'dispatchEvent', [event]);
}
}
Update
Since direct DOM access isn't discouraged anymore by the Angular team this simpler code can be used as well
this.fileInput.nativeElement.click()
See also https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
I also wanted similar functionality where I have a File Input Control with display:none and a Button control where I wanted to trigger click event of File Input Control when I click on the button, below is the code to do so
<input type="button" (click)="fileInput.click()" class="btn btn-primary" value="Add From File">
<input type="file" style="display:none;" #fileInput/>
as simple as that and it's working flawlessly...
This worked for me:
<button #loginButton ...
and inside the controller:
#ViewChild('loginButton') loginButton;
...
this.loginButton.getNativeElement().click();
To get the native reference to something like an ion-input, ry using this
#ViewChild('fileInput', { read: ElementRef }) fileInput: ElementRef;
and then
this.fileInput.nativeElement.querySelector('input').click()
Günter Zöchbauer's answer is the right one. Just consider adding the following line:
showImageBrowseDlg() {
// from http://stackoverflow.com/a/32010791/217408
let event = new MouseEvent('click', {bubbles: true});
event.stopPropagation();
this.renderer.invokeElementMethod(
this.fileInput.nativeElement, 'dispatchEvent', [event]);
}
In my case I would get a "caught RangeError: Maximum call stack size exceeded" error if not. (I have a div card firing on click and the input file inside)
If you want to imitate click on the DOM element like this:
<a (click)="showLogin($event)">login</a>
and have something like this on the page:
<li ngbDropdown>
<a ngbDropdownToggle id="login-menu">
...
</a>
</li>
your function in component.ts should be like this:
showLogin(event) {
event.stopPropagation();
document.getElementById('login-menu').click();
}