Reputation: 1995
I am new to angular2, i have an issue with my input which has an attribute autoGorw it is a custom directive and has two events
(focus) and (blur), onFocus()
i want to increase the input size and onBlur()
i want to decrease the size to its default size, both the events
been firing and show results in console, but input
size is not increasing, there isn't any error in my console, i don't know what i am missing.
Sorry i tried in Plunker
for live demo to make you easy to understand, but couldn't made one.
Here is my code
auto-grow.directive.ts
import {Directive, ElementRef, Renderer} from '@angular/core'
// ElementRef => Gives access to host element
// Renderer => Gives access to modify that element
@Directive({
selector: '[autoGrow]',
host:{
'(focus)' : 'onFocus()',
'(blur)' : 'onBlur()'
}
})
export class AutoGrowDirective{
constructor(private el : ElementRef, private renderer : Renderer){
}
onFocus(){
console.log("Triggered !"); // its working upto this line.
this.renderer.setElementStyle(this.el.nativeElement,'Width','500');
}
onBlur(){
this.renderer.setElementStyle(this.el.nativeElement,'Width','120');
}
}
courses.component.ts
import {Component} from '@angular/core'
import {AutoGrowDirective} from './auto-grow.directive'
@Component({
selector:"courses",
template:`
<h2>This is Courses component</h2>
<p>{{ title }}</p>
<input type="text" autoGrow />
`,
directives: [AutoGrowDirective]
})
export class CoursesComponent{
title = 'This is the title of Courses Page!';
}
app.component.ts
import { Component } from '@angular/core';
import {CoursesComponent} from './courses.component';
@Component({
selector: 'my-app',
template: '<h1>Hello Angular!</h1><courses></courses>',
directives:[CoursesComponent]
})
export class AppComponent { }
HTML
In html inside body i have the selector
<my-app>Loading Please wait...</my-app>
Upvotes: 3
Views: 5238
Reputation: 877
Adding 'px' to the width works fine for me.
import { Directive, ElementRef, Renderer } from '@angular/core';
@Directive({
selector: '[autoGrow]',
host: {
'(focus)': 'onFocus()',
'(blur)': 'onBlur()'
}
})
export class AutoGrowDirective {
constructor(private el: ElementRef, private renderer: Renderer) {
}
onFocus() {
this.renderer.setElementStyle(this.el.nativeElement, 'width', '200px');
}
onBlur() {
this.renderer.setElementStyle(this.el.nativeElement, 'width', '100px');
}
}
Upvotes: 3
Reputation: 657871
I guess you are only missing px
in '500px'
and 'width'
should be lowercase.
I would do it this way though:
@Directive({
selector: '[autoGrow]',
})
export class AutoGrowDirective {
@HostBinding('style.width.px')
width:number = 120;
@HostListener('focus')
onFocus() {
this.width=500;
}
@HostListener('blur')
onBlur(){
this.width = 120;
}
}
Upvotes: 10