7

I cannot find a way to manage through Angular 2 how a custom input gets its focus from a label (and its for attribute) and how to manage those states.

I'm trying to give my the same focus-and-blur behaviour that a regular has. Any ideas on that?

Thanks!

Andrés Fulla
  • 71
  • 1
  • 3
  • See http://stackoverflow.com/questions/34522306/angular-2-focus-on-newly-added-input-element. If this is not enough please provide more information about what the problem is. – Günter Zöchbauer Nov 10 '16 at 11:02
  • 1
    Thanks for your reply. I don't think that link tackles the same issue. What I'm trying to do is to give my the same focus and blur behaviour that a regular has. I'll update the question so is better understandable. – Andrés Fulla Nov 10 '16 at 12:00

2 Answers2

9

HTML have tabindex attribute, that makes any element focusable. http://w3c.github.io/html/editing.html#the-tabindex-attribute

Then in component you can listen focus event:

 @HostBinding('tabindex') tabindex = 0;

 @HostListener('focus')
 focusHandler() {
   alert('focused!');
 }
Navix
  • 116
  • 2
  • 7
  • 1
    The key to this answer is `tabindex` if the host element used for the custom control does not normally allow focus. Instead of using `@HostListener` you can add '(focus)' to the Component decorator's `host` entry. – Precastic Nov 06 '18 at 21:12
0

With accessibility in mind, every input must contain a label, so an input component should contain the input and label tags

imports...

@Component({
      selector: 'app-input',
      templateUrl: 
          `<label [for]="id">
              <div class="label">{{label}}</div>
              <input [id]="id"
                     [type]="type"
                     [attr.maxlength]="maxlength"
                     [autocomplete]="autocomplete"
                     [placeholder]="placeholder"
                     (input)="onInput($event)"
                     (focus)="onFocus()"
                     required
                 >
          </label>`,
      styleUrls: ['./input.component.scss'],
})

export class InputComponent{

  @Input() label: string;
  @Input() id: string;
  @Input() type: string;
  @Input() maxlength: string;
  @Input() autocomplete = "on";
  @Input() disabled = null;

  onInput(event: any){
      ....
  }

  onFocus(){
      ....
  }
}