【问题标题】:How can I manage focus states on an Angular 2 custom input component?如何管理 Angular 2 自定义输入组件的焦点状态?
【发布时间】:2017-03-24 09:06:10
【问题描述】:

我找不到通过 Angular 2 管理自定义输入如何从 label(及其 for 属性)获得焦点以及如何管理这些状态的方法。

我正在尝试提供与普通人相同的专注和模糊行为。有什么想法吗?

谢谢!

【问题讨论】:

  • stackoverflow.com/questions/34522306/…。如果这还不够,请提供有关问题所在的更多信息。
  • 感谢您的回复。我不认为该链接解决了同样的问题。我想要做的是让我的 具有与常规 相同的焦点和模糊行为。我会更新这个问题,以便更好地理解。

标签: angular focus custom-element


【解决方案1】:

HTML 具有 tabindex 属性,这使得任何元素都可以聚焦。 http://w3c.github.io/html/editing.html#the-tabindex-attribute

然后在组件中可以监听焦点事件:

 @HostBinding('tabindex') tabindex = 0;

 @HostListener('focus')
 focusHandler() {
   alert('focused!');
 }

【讨论】:

  • 如果用于自定义控件的宿主元素通常不允许焦点,则此答案的关键是 tabindex。除了使用@HostListener,您还可以将'(focus)' 添加到组件装饰器的host 条目中。
【解决方案2】:

考虑到可访问性,每个输入都必须包含一个标签,因此输入组件应该包含输入和标签标签

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(){
      ....
  }
}

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 2017-06-05
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2023-02-14
    相关资源
    最近更新 更多