Change event with jQuery datepicker and Angular 2 - javascript

I have some problems to catch the change event when I use the jQuery datepicker plugin and I'm trying to use the (change) method to catch the change but seems that when I'm using this plugin, angular can't catch it.
#Component({
selector: 'foo-element',
template: '<input type="text" (change)="checkDates($event)" id="foo_date_picker" class="datepicker">'
})
export class FooComponentClass implements AfterViewInit {
ngAfterViewInit():any{
$('#end_day').datepicker();
}
private function checkDates(e){
console.log("Please, catch the change event ): ");
}
}
I have removed the datepicker initialization and works fine, but when I use it again... don't works.
Someone can help me!
Thanks so much.

You could implement the following directive:
#Directive({
selector: '[datepicker]'
})
export class DatepickerDirective {
#Output()
change:EventEmitter<string> = new EventEmitter();
constructor(private elementRef:ElementRef) {
}
ngOnInit() {
$(this.elementRef.nativeElement).datepicker({
onSelect: (dateText) => {
this.change.emit(dateText);
}
});
}
}
This way you will be able to catch a change event like this:
#Component({
selector: 'app',
template: '<input type="text" id="end_day" (change)="checkDates($event)" class="datepicker" datepicker>',
directives: [ DatepickerDirective ]
})
export class App implements AfterViewInit {
checkDates(e){
console.log("Please, catch the change event ): "+e);
}
}
See this plunkr: https://plnkr.co/edit/TVk11FsItoTuNDZLJx5X?p=preview

Related

Use injected dependency in jQuery event listener in angular

I'm using Bootstrap 4 modals in Angular 6 and I want to redirect the user to another route once the modal is closed. However, I'm getting a scoping issue when the modal is closed telling me that my injected router is undefined.
My code:
import { Component, OnInit } from '#angular/core';
declare var $: any
#Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {
constructor(
public router: Router
) {}
ngOnInit() {}
ngAfterViewInit() {
$('#mymodal').on('hidden.bs.modal', function (e) {
router.navigate(['/']) //tells me that router is undefined
})
}
}
Use this keyword like that in Jquery.
ngAfterViewInit() {
var self = this;
$('#mymodal').on('hidden.bs.modal', function (e) {
self.router.navigate(['/']);
})
}
Use this to have access to the router as an injected dependency and arrow function syntax((e) => {}) to rescope it to the correct scope. Like this:
ngAfterViewInit() {
$('#mymodal').on('hidden.bs.modal', (e) => {
this.router.navigate(['/']);
})
}

How to add an Angular property to an HTML element

I need to know how to add to an html button the property (click) = function() of angular through Javascript.
Note: I cannot modify the HTML, I can only add the property through JavaScript.
I tested with addEventListener and it works by adding the common JavaScript click = "function" event, but not the (click) of Angular.
I attach the code:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-iframe',
templateUrl: './iframe.component.html',
styleUrls: ['./iframe.component.scss']
})
export class IframeComponent implements OnInit {
constructor() {}
ngOnInit() {
}
capture() {
let button = document.getElementById('cancelButton').addEventListener('(click)', this.cancel.bind(Event));
}
cancel() {
console.log('Cancelled');
}
}
And the HTML here:
<div class="row text-center pad-md">
<button id="acceptButton" mat-raised-button color="primary">OK!</button>
<button id="cancelButton" mat-raised-button>Cancel</button>
</div>
As stated by the author, the event need to be attached dynamically to the DOM element that is created after a request, so you can use Renderer2
to listen for the click event. Your code should look like this:
import { Component, OnInit, Renderer2 } from '#angular/core';
#Component({
selector: 'app-iframe',
templateUrl: './iframe.component.html',
styleUrls: ['./iframe.component.scss']
})
export class AppComponent implements OnInit {
name = 'Angular';
constructor(private renderer: Renderer2) {}
ngOnInit() {}
capture() {
const button = document.getElementById('cancelButton');
console.log(button);
this.renderer.listen(button, 'click', this.cancel);
}
cancel() {
console.log('Cancelled');
}
}
There's a functional example here.

Angular #Output not working

Trying to do child to parent communication with #Output event emitter but is no working
here is the child component
import { Component, OnInit, Output, Input, EventEmitter } from '#angular/core';
#Component({
selector: 'app-emiter',
templateUrl: './emiter.component.html',
styleUrls: ['./emiter.component.css']
})
export class EmiterComponent implements OnInit {
#Output() emitor: EventEmitter<any>
constructor() { this.emitor = new EventEmitter()}
touchHere(){this.emitor.emit('Should Work');
console.log('<><><><>',this.emitor) // this comes empty
}
ngOnInit() {
}
}
this is the html template
<p>
<button (click)=" touchHere()" class="btn btn-success btn-block">touch</button>
</p>
The console.log inside the touchHere it shows nothing
even if I put this inside the parent component it show nothing as well
parent component
import { Component , OnInit} from '#angular/core';
// service I use for other stuff//
import { SenderService } from './sender.service';
// I dont know if I have to import this but did it just in case
import { EmiterComponent } from './emiter/emiter.component'
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
user: any;
touchThis(message: string) {
console.log('Not working: ${message}');
}
constructor(private mySessionService: SenderService) { }
}
and here is the html template
<div>
<app-emiter>(touchHere)='touchThis($event)'</app-emiter>
</div>
Parent component template:
<app-emitor (emitor)='touchThis($event)'></app-emiter>
In parent template #Output should be 'called', not the child method.
Also, see: https://angular.io/guide/component-interaction#parent-listens-for-child-event
Here’s an example of how we write a component that has outputs:
#Component({
selector: 'single-component',
template: `<button (click)="liked()">Like it?</button>`
})
class SingleComponent {
#Output() putRingOnIt: EventEmitter<string>;
constructor() {
this.putRingOnIt = new EventEmitter();
}
liked(): void {
this.putRingOnIt.emit("oh oh oh");
}
}
Notice that we did all three steps: 1. specified outputs, 2. created an EventEmitter that we attached
to the output property putRingOnIt and 3. Emitted an event when liked is called.
If we wanted to use this output in a parent component we could do something like this:
#Component({
selector: 'club',
template: `
<div>
<single-component
(putRingOnIt)="ringWasPlaced($event)"
></single-component>
</div>`
})
class ClubComponent {
ringWasPlaced(message: string) { console.log(`Put your hands up: ${message}`);
} }
// logged -> "Put your hands up: oh oh oh"
Again, notice that:
putRingOnIt comes from the outputs of SingleComponent
ringWasPlaced is a function on the ClubComponent
$event contains the thing that wasemitted, in this case a string
<app-emiter (emitor)="touchThis($event)" ></app-emiter>
By using #Output() you should apply the event you need to emit in the directive of the emitter component.Adding the name of the variable to the the directive and but the emitted over function inside the quotation passing the $event.
touchHere() is the method from which you are binding some value to emit with your EventEmitter. And your EventEmitter is 'emitor'.
So your code will work if you simply do the below:
<app-emiter (emitor)='touchThis($event)'></app-emiter>

In Angular2 ngModel value not updating on onBlur event of custom directive

I have developed a custom directive which trims value of input controls.
Please find the code for the same:
import { Directive, HostListener, Provider } from '#angular/core';
import { NgModel } from '#angular/forms';
#Directive({
selector: '[ngModel][trim]',
providers: [NgModel],
host: {
'(ngModelChange)': 'onInputChange($event)',
'(blur)': 'onBlur($event)'
}
})
export class TrimValueAccessor {
onChange = (_) => { };
private el: any;
private newValue: any;
constructor(private model: NgModel) {
this.el = model;
}
onInputChange(event) {
this.newValue = event;
console.log(this.newValue);
}
onBlur(event) {
this.model.valueAccessor.writeValue(this.newValue.trim());
}
}
The problem is ngModel not updating value on onBlur event.
I tried to trim value on onModelChange event but it doesn't allow space between two words(e.g., ABC XYZ)
Any suggestion would be helpful.
Please add below lines of code in onblur event instead of existing code.It would work:
this.model.control.setValue(this.newValue.trim());
Thanks!

Angular2 on focus event to add class

I'm looking to update an Angular 1 app to Angular 2 and am having an issue with one of my old directives.
The idea is simple. When an input field is focused a class should be added (md-input-focus) and another be removed (md-input-wrapper). Then this process should be reversed on "blur" event - i.e. focus lost.
My old directive simply included the lines
.directive('mdInput',[
'$timeout',
function ($timeout) {
return {
restrict: 'A',
scope: {
ngModel: '='
},
link: function (scope, elem, attrs) {
var $elem = $(elem);
$elem.on('focus', function() {
$elem.closest('.md-input-wrapper').addClass('md-input-focus')
})
.on('blur', function() {
$(this).closest('.md-input-wrapper').removeClass('md-input-focus');
})
}
etc...
I obviously have the classic start to my directive but have run out of.....skill
import {Directive, ElementRef, Renderer, Input} from 'angular2/core';
#Directive({
selector: '.mdInput',
})
export class MaterialDesignDirective {
constructor(el: ElementRef, renderer: Renderer) {
// Insert inciteful code here to do the above
}
}
Any help would be appreciated.
UPDATE:
The HTML would look like (before the input element was focused):
<div class="md-input-wrapper">
<input type="text" class="md-input">
</div>
and then
<div class="md-input-wrapper md-input-focus">
<input type="text" class="md-input">
</div>
after.
The input element is the only one which can receive a focus event (and therefore the target for the directive) however the parent <div> requires the class addition and removal.
Further help
Please see Plunker for help/explanation - would be great if someone could help
Update
#Directive({selector: '.md-input', host: {
'(focus)': 'setInputFocus(true)',
'(blur)': 'setInputFocus(false)',
}})
class MaterialDesignDirective {
MaterialDesignDirective(private _elementRef: ElementRef, private _renderer: Renderer) {}
setInputFocus(isSet: boolean): void {
this.renderer.setElementClass(this.elementRef.nativeElement.parentElement, 'md-input-focus', isSet);
}
}
Original
This can easily be done without ElementRef and Renderer (what you should strive for in Angular2) by defining host bindings:
import {Directive, ElementRef, Renderer, Input} from 'angular2/core';
#Directive({
selector: '.mdInput',
host: {
'(focus)':'_onFocus()',
'(blur)':'_onBlur()',
'[class.md-input-focus]':'inputFocusClass'
}
})
export class MaterialDesignDirective {
inputFocusClass: bool = false;
_onFocus() {
this.inputFocusClass = true;
}
_onBlur() {
this.inputFocusClass = false;
}
}
or a bit more terse
#Directive({
selector: '.mdInput',
host: {
'(focus)':'_setInputFocus(true)',
'(blur)':'_setInputFocus(false)',
'[class.md-input-focus]':'inputFocusClass'
}
})
export class MaterialDesignDirective {
inputFocusClass: bool = false;
_setInputFocus(isFocus:bool) {
this.inputFocusClass = isFocus;
}
}
I tried it only in Dart where it works fine. I hope I translated it correctly to TS.
Don't forget to add the class to the directives: of the element where you use the directive.
In addition to previous answers, if you don't want to add a directive, for the specific component (you already have a directive for a parent component, you are using Ionic 2 page or something else), you inject the renderer by adding private _renderer: Renderer in the page constructor and update the element using the event target like this:
html:
(dragstart)="dragStart($event)"
TS:
dragStart(ev){
this._renderer.setElementClass(ev.target, "myClass", true)
}
Edit: to remove the class just do:
dragEnd(ev){
this._renderer.setElementClass(ev.target, "myClass", false)
}
The name of the selector has to be inside "[ ]", as shown below
#Directive({
selector: '[.mdInput]',
host: {
'(focus)':'_setInputFocus(true)',
'(blur)':'_setInputFocus(false)',
'[class.md-input-focus]':'inputFocusClass'
}
})
If you want to catch the focus / blur events dynamiclly on every input on your component :
import { AfterViewInit, Component, ElementRef } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
name = 'Angular focus / blur Events';
constructor(private el: ElementRef) {
}
ngAfterViewInit() {
// document.getElementsByTagName('input') : to gell all Docuement imputs
const inputList = [].slice.call((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
inputList.forEach((input: HTMLElement) => {
input.addEventListener('focus', () => {
input.setAttribute('placeholder', 'focused');
});
input.addEventListener('blur', () => {
input.removeAttribute('placeholder');
});
});
}
}
Checkout the full code here : https://stackblitz.com/edit/angular-wtwpjr

Categories