簡體   English   中英

我們如何使用 angular 2+ 組件中的輸入:焦點選擇器?

[英]How do we use the input:focus selector in angular 2+ component?

我有一個包含以下內容的表單:

<div class="form-field">
<input-component [tabIndex]="tabData.tabEnable"></input-component>
</div>
<div class="form-field">
<input [tabIndex]="tabData.tabEnable" matInput cgiPrecision type="number"/>
</div>

在 css 我有這個:

input:focus {
border: $border-width solid $darkblue
}

但是邊框只顯示在輸入元素上,而不是在其中包含輸入輸入組件組件上。 如何獲得輸入:焦點也適用於自定義 angular 組件?

您的自定義組件應偵聽focus事件,然后聚焦輸入。

@Component({
  selector: 'custom-input',
  template: `<input #myInput type="text" [(ngModel)]="innerValue">`,
  styles: [`
    input {border: 5px solid green; } 
    input:focus { border: 5px solid blue; }
  `]
})
export class CustomInputComponent implements ControlValueAccessor  {

  @ViewChild('myInput', {static: false}) inputCtrl;

  //...functions to implement ControlValueAccessor

  @HostListener('focus')
  focusHandler() {
   this.inputCtrl.nativeElement.focus();
 }
}

這是一個stackblitz演示。

scss 文件僅限於其 angular 組件。 如果要全局使用 css,請使用style.scss

另一種選擇是,使用style-urls數組將 scss 集成到您的子組件中:

@Component({
  selector: 'input-component',
  templateUrl: '/input-component.html',
  styleUrls: [
    './input-component.scss',             // own scss file
    './../path-to-other-compontent.scss'  // <--- here
  ]
})
export class InputComponent {
  [...]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM