增加焦点输入的宽度为angular2

时间:2016-07-01 12:19:27

标签: angular

我是angular2的新手,我的输入有一个问题,它有一个 autoGorw 属性,它是一个自定义指令,有两个events (焦点)和(模糊)onFocus()我想增加输入大小,onBlur()我希望将大小减小到默认大小events在控制台中触发并显示结果,但input大小没有增加,我的控制台中没有任何错误,我不知道我错过了什么。

很抱歉我在Plunker尝试了现场演示,让您轻松理解,但无法制作。

这是我的代码

自动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

在html体内,我有选择器

<my-app>Loading Please wait...</my-app>

2 个答案:

答案 0 :(得分:10)

我猜您在px中只丢失了'500px',而'width'应该是小写的。{/ p>

我会这样做:

@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;
  }
}

Plunker example

答案 1 :(得分:3)

为宽度添加'px'对我来说很好。

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