【问题标题】:In Angular, how to implement button:focus outline: none in a directive在 Angular 中,如何在指令中实现 button:focus outline: none
【发布时间】:2020-11-16 17:32:50
【问题描述】:

在我的 css 文件中,我为我的按钮设置了大纲:无。

.my-btn:focus {
outline: none;
} 

现在我想为我的按钮创建一个指令,该指令也将执行此操作。这样的指令怎么写?

提前致谢。

【问题讨论】:

    标签: css angular angular-directive angular2-directives


    【解决方案1】:

    您可以根据您的要求创建一个指令并在焦点/fousin 上设置一个 @HostListener

    @HostListener('focus')

    并使用ElementRef设置nativeElement.style.outline = none;

    【讨论】:

      【解决方案2】:
      • 使用ng g d unfocus-btn 创建您的自定义指令
      • 在UnfocusButtonDirective.ts中编写如下代码;

      @Directive({ selector: '[unfocus]' })

      export class UnfocusButtonDirective {
      
        constructor(private el: ElementRef) { }
      
        @HostListener('focus')
        private onButtonFocus() {
          this.el.nativeElement.style.outline = 'none';
        }
      
      }
      
      • 在需要该指令的 HTML 中使用

      <button type="button" unfocus >Submit</button> // 在此处添加指令

      • 在最近的 module.ts 文件或 app.module.ts 文件中声明您的指令

      @NgModule({ declarations: [UnfocusButtonDirective] })

      就是这样。一切就绪。

      【讨论】:

        猜你喜欢
        • 2021-06-21
        • 1970-01-01
        • 1970-01-01
        • 2018-03-31
        • 2021-06-01
        • 1970-01-01
        • 2014-11-09
        • 1970-01-01
        • 2016-12-29
        相关资源
        最近更新 更多