I have a toggle button and two functions. I want one of the functions to be called when the toggle button is on, and the other to be called when the toggle button is in off state. How can I do that?
This is really easy actually if you make use of angular forms. You just need to subscribe to the toggle control that we define in the FormGroup. You can subscribe to the value of the entire form or just the value of an individual control as I've done below. Following the angular documentation, I usually use a separate function to construct my FormGroup and then call that function, buildForm() inside the constructor.
buildForm(): void {
this.myCoolForm = this._fb.group({
superCoolToggle: ['']
})
this.form.controls['superCoolToggle'].valueChanges.subscribe( value => {
if (value === true) {
// something here
} else if (value === false) {
// something different here
}
})
}
<form [formGroup]="myCoolForm">
<ion-item>
<ion-label> Sam</ion-label>
<ion-toggle formControlName="superCoolToggle"></ion-toggle>
</ion-item>
</form>
Related
I am trying to add a click listener to a button in a leaftlet popup in my ionic app.
Here I am creating the map & displaying markers, also the method I want called when the header tag is clicked is also below:
makeCapitalMarkers(map: L.map): void {
let eventHandlerAssigned = false;
this.http.get(this.capitals).subscribe((res: any) => {
for (const c of res.features) {
const lat = c.geometry.coordinates[0];
const lon = c.geometry.coordinates[1];
let marker = L.marker([lon, lat]).bindPopup(`
<h4 class="link">Click me!</h4>
`);
marker.addTo(map);
}
});
map.on('popupopen', function () {
console.log('Popup Open')
if (!eventHandlerAssigned && document.querySelector('.link')) {
console.log('Inside if')
const link = document.querySelector('.link')
link.addEventListener('click', this.buttonClicked())
eventHandlerAssigned = true
}
})
}
buttonClicked(event) {
console.log('EXECUTED');
}
When I click this header, Popup Open & Inside if are printed in the console, so I know I'm getting inside the If statement, but for some reason the buttonClicked() function isn't being executed.
Can someone please tell me why this is the current behaviour?
I just ran into this issue like 2 hours ago. I'm not familiar with ionic, but hopefully this will help.
Create a variable that keeps track of whether or not the content of your popup has an event handler attached to it already. Then you can add an event listener to the map to listen for a popup to open with map.on('popupopen', function(){}). When that happens, the DOM content in the popup is rendered and available to grab with a querySelector or getElementById. So you can target that, and add an event listener to it. You'll have to also create an event for map.on('popupclose', () => {}), and inside that, remove the event listener from the dom node that you had attached it to.
You'd need to do this for every unique popup you create whose content you want to add an event listener to. But perhaps you can build a function that will do that for you. Here's an example:
const someMarker = L.marker(map.getCenter()).bindPopup(`
<h4 class="norwayLink">To Norway!</h4>
`)
someMarker.addTo(map)
function flyToNorway(){
map.flyTo([
47.57652571374621,
-27.333984375
],3,{animate: true, duration: 5})
someMarker.closePopup()
}
let eventHandlerAssigned = false
map.on('popupopen', function(){
if (!eventHandlerAssigned && document.querySelector('.norwayLink')){
const link = document.querySelector('.norwayLink')
link.addEventListener('click', flyToNorway)
eventHandlerAssigned = true
}
})
map.on('popupclose', function(){
document.querySelector('.norwayLink').removeEventListener('click', flyToNorway)
eventHandlerAssigned = false
})
This is how I targeted the popup content and added a link to it in the demo for my plugin.
So yes you can't do (click) event binding by just adding static HTML. One way to achieve what you want can be by adding listeners after this new dom element is added, see pseudo-code below:
makeCapitalMarkers(map: L.map): void {
marker.bindPopup(this.popUpService.makeCapitalPopup(c));
marker.addTo(map);
addListener();
}
makeCapitalPopup(data: any): string {
return `` +
`<div>Name: John</div>` +
`<div>Address: 5 ....</div>` +
`<br/><button id="myButton" type="button" class="btn btn-primary" >Click me!</button>`
}
addListener() {
document.getElementById('myButton').addEventListener('click', onClickMethod
}
Ideally with Angular, we should not directly be working with DOM, so if this approach above works you can refactor adding event listener via Renderer.
Also I am not familiar with Leaflet library - but for the above approach to work you need to account for any async methods (if any), so that you were calling getElementById only after such DOM element was successfully added to the DOM.
I have a list containing users, and i have an item that i want it to redirect me to a modal page.
My problem is as soon as my page is available, i get an infinite pop up of my modal, instead of going on my ion-select and select the item so i can get the pop up.
html
<ion-select interface="popover" (ngModelChange)="onChange($event)">
<ion-option>Bacon</ion-option>
<ion-option [value]="openConfig()"></ion-option>Black Olives</ion-option>
<ion-option>Extra Cheese</ion-option>
<ion-option>Mushrooms</ion-option>
<ion-option>Pepperoni</ion-option>
<ion-option>Sausage</ion-option>
</ion-select>
ts
onChange(value: any) {
if (value === 'openConfig') {
this.openConfig()
}
}
openConfig() {
this.modalCtrl.create('ConfigModal').present;
console.log('heeey')
}
Setting the [value] in the template is actually calling your openConfig() function, creating an infinite loop on the page load. To do what you're trying to do here you don't need to reference your openConfig function in the template at all.
ion-select uses the output event ionChange, which outputs the value of the ion-option selected. So the normal way to do this in Ionic 3 would be something like this:
html:
<ion-content padding>
<ion-select interface="popover" [ngModel]="option" (ionChange)="onChange($event)">
<ion-option>Bacon</ion-option>
<ion-option>Black Olives</ion-option>
<ion-option>Extra Cheese</ion-option>
<ion-option>Mushrooms</ion-option>
<ion-option>Pepperoni</ion-option>
<ion-option>Sausage</ion-option>
</ion-select>
</ion-content>
js:
onChange(value: any) {
if (value === 'Black Olives') {
this.openConfig()
}
}
openConfig() {
this.modalCtrl.create(ConfigModal).present();
}
Note that the value of an ion-option is simply the text of the label. So that's what you should check for in your "onChange" function.
You have a couple of other unrelated typos, but I believe this addresses the question of your infinite loop. Hope this helps!
I have a requirement for my app and I need to change the event handler of a common button depending on the status of the workflow.
Basically I need to change the function called when you press the button and vice-versa and was looking to achieve this by using the event handler functions detachPress and attachPress.
https://ui5.sap.com/#/api/sap.m.Button/methods/detachPress
https://ui5.sap.com/#/api/sap.m.Button/methods/attachPress
My Button (XML View):
<Button text="Edit" width="50%" id="_editButtonEmail" press="editPIN"/>
On my controller I want to change the function editPIN by cancelEditPIN.
Some things I've tried:
editPIN: function(oControlEvent) {
//change button
var editButton = this.getView().byId("_editButtonEmail");
//detach this function on press
editButton.detachPress(editButton.mEventRegistry.press[0].fFunction);
editButton.attachPress(this.cancelEditPIN());
}
cancelEditPIN: function() {
//do something else
}
Also
editPIN: function(oControlEvent) {
//change button
var src = oControlEvent.getSource();
src.detachPress(this.editPIN());
src.attachPress(this.cancelEditPIN());
}
None of these seem to work and if I check my console the function editPIN is still attached to my mEventRegistry press event.
There are few things worse than checking your GUI texts to determine what action should be done.
A different approach uses two buttons. Only one is visible at a time
<Button
text="{i18n>editPIN}"
visible="{= ${myModel>/State} === 'show' }"
press="editPIN" />
<Button
text="{i18n>editCancelPIN}"
visible="{= ${myModel>/State} === 'edit' }"
press="cancelEditPIN" />
In this case {myModel>/State} is a local JSON model where the current state of your workflow is stored.
If you really want to use your attach/detach approach: It probably didn't work because you were calling the methods while passing them as a parameter to attach/detach. So for example try src.detachPress(this.editPIN); instead of src.detachPress(this.editPIN());
Following the idea from #Jorg, I created another function checkPIN with an if statement that compares the text in the button and then fires the appropriate function depending on it.
I do have to phrase that I am using my i18n file to provide texts to my view, this way my textID will not change on whatever language the user is using.
My Button:
<Button text="Edit" width="50%" id="_editButtonEmail" press="checkPIN"/>
My Controller:
checkPIN: function(oControlEvent) {
var src = this.getView().byId("_editButtonEmail").getText();
var oBundle = this.getView().getModel("i18n").getResourceBundle();
//call cancelEditPIN
var editCancelPinText = oBundle.getText("editCancelPIN");
//call editPIN
var editPinText = oBundle.getText("editPIN");
//change button
if (src === editPinText) {
this.editPIN(oBundle);
} else if (src === editCancelPinText) {
this.cancelEditPIN(oBundle);
}
},
editPIN: function(oBundle) {
//do stuff here
//change button text
var editButton = this.getView().byId("_editButtonEmail");
editButton.setText(oBundle.getText("editCancelPIN"));
},
cancelEditPIN: function(oBundle) {
//do different stuff here
//change button text
var editButton = this.getView().byId("_editButtonEmail");
editButton.setText(oBundle.getText("editPIN"));
}
Not really the answer I was looking for because I would like to use detachPress and attachPress so if you know what I should have done in order to implement those please let me know.
I have a nav component which I am using on 4 pages, I want to be able to change the color of active page's button in the nav component. In Ionic app doc's for nav controller I found getActive() instance, but I can't figure out how to achieve the desired result with it. I'm using the following code to push to a new view.
viewPage2(){
this.navCtrl.push(Page2);
}
<button ion-button (click)="viewPage2()" color="dark" clear full>Page 2</button>
NavController getActive() returns the ViewController of the Active page.
Looking at the API of ViewController you could try using getContentRef():
this.navCtrl.getActive().contentRef().nativeElement.getElementById("button_id")
Once you have the element you could change the color.
Even though getting the html element by its id may work, modifying the DOM directly is not the recommended way to do things in Ionic.
First option:
If that's a custom component, you can always expose a public method in that component, and get the reference by using ViewChild
#Component({...})
export class NavCustomComponent {
public activePage: string = 'page1';
//...
public changeActivePage(pageName: string): void {
this.activePage = pageName;
}
// ...
}
And in your view:
<button ion-button (click)="viewPage2()" [color]="activePage === 'page2' ? 'light' : 'dark'" clear full>Page 2</button>
Then in the page where you're trying to modify the component:
#Component({...})
export class DemoPage {
#ViewChild(NavCustomComponent) navCustomComponent: NavCustomComponent;
}
and then use that reference to call that public method:
this.navCustomComponent.changeActivePage('page2');
Second option:
If that's not a custom component, or you just want to make things even simpler, you can just Events. Whereever you're defining the code of that nav component, (or in your app.component.ts file to make it global for the entire app) subscribe to the event:
public activePage: string = 'page1';
constructor(public events: Events, ...) {
events.subscribe('page:selected', (pageName) => {
this.activePage = pageName;
});
}
Again, in your view:
<button ion-button (click)="viewPage2()" [color]="activePage === 'page2' ? 'light' : 'dark'" clear full>Page 2</button>
And then in the component where you want to change the color, just publish that event:
events.publish('page:selected', 'page2');
Knockout doesn't update observables when a form reset button is clicked.
http://jsfiddle.net/nQXeM/
HTML:
<form>
<input type="text" data-bind="value: test" />
<input type="reset" value="reset" />
</form>
<p data-bind="text: test"></p>
JS:
function ViewModel() {
this.test = ko.observable("");
}
ko.applyBindings(new ViewModel());
Clearly the change event of the input box isn't being fired, as seen with this jQuery test:
http://jsfiddle.net/LK8sM/4/
How would we go about forcing all observables bound to form inputs to update without having to manually specify them if the reset button isn't firing of change events?
It would be easy enough to use jQuery to find all inputs inside the form and trigger change events, but lets assume we've a knockout only controlled form.
I copied and modified the default Knockout submit binding in order to create a similar binding for the form reset event:
ko.bindingHandlers['reset'] = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
if (typeof valueAccessor() !== 'function')
throw new Error('The value for a reset binding must be a function');
ko.utils.registerEventHandler(element, 'reset', function (event) {
var handlerReturnValue;
var value = valueAccessor();
try {
handlerReturnValue = value.call(bindingContext['$data'], element);
} finally {
if (handlerReturnValue !== true) {
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
});
}
};
You'd bind this like:
<form data-bind="reset: onFormReset">
and onFormReset would be on your view model:
function ViewModel() {
this.onFormReset = function () {
//Your custom logic to notify or reset your specific fields.
return true;
}
}
In your reset handler, if you return true, then JavaScript will continue to call its reset function on the form. If you are setting observables that are bound to value, though, you don't really need to have JavaScript continue to reset the form. Therefore, you could technically not return anything, or return false in that scenario.
Someone else could extend this further to notify all the bound observables in the form automatically, but this worked for my purposes.
As you mentioned, the change event isn't fired when a form is reset. If you're only using KnockOut, I don't think you really have may options unless you create custom bindings that can register for the reset event and detect changes - that would still involve manual JS, but at least it would be centralized.
A more general approach, although it does require jQuery, is to create a function to handle the form's reset event, and detect changes on the form inputs at that time.
Here's an example of an event handler that might work. Please be aware, this is not production-ready code. I would look at it with a good jQuery eye before using :)
$('form').on('reset', function (evt) {
evt.preventDefault();
$(this).find('input, select, textarea').each(function () {
if ($(this).is('input[type="radio"], input[type="checkbox"]')) {
if ($(this).is(':checked') !== $(this)[0].defaultChecked) {
$(this).val($(this)[0].defaultChecked);
$(this).trigger('click');
$(this).trigger('change');
}
} else {
if ($(this).val() !== $(this)[0].defaultValue) {
$(this).val($(this)[0].defaultValue);
$(this).change();
}
}
});
});
Here's a fiddle that demonstrates the idea: http://jsfiddle.net/Fm8rM/2/