在servive.ts中使用@ViewChildren导致未定义

时间:2019-06-17 09:01:33

标签: angular

如果我使用ViewChildren查找某些特定元素,则会收到未定义的错误,因为我正在服务中使用它。如果服务在多个HTML文件中使用,如何在服务中加载子级?

export class FormControlService {

  @ViewChildren('focusable', {read: ElementRef}) focusableField: QueryList<ElementRef>;

........
........
........

 setFocusDurchLink(event) {

    this.dialogSektionen.forEach(element => {

        if (element.sektionTitel === event.target.innerHTML) {

          for (let i = 0; i < this.focusableField.length; i++) { // <-- Here undefined

...

}

2 个答案:

答案 0 :(得分:1)

您可以使用getter和setter进行管理。它使代码更易于阅读。

Here is a working stackblitz

export class AppComponent {

  get divs() { return this.service.divs; }

  @ViewChildren('divs') 
  set divs(value: QueryList<ElementRef<HTMLDivElement>>) {
    // For lifecycle error, use timeout
    setTimeout(() => this.service.divs = value);
  }

  constructor(
    public service: MyService
  ) { }
}
export class MyService {

  public divs: QueryList<ElementRef<HTMLDivElement>>;

  constructor() { }

}
<div *ngFor="let i of [1, 2, 3]" #divs>div n° {{ i }}</div>

<br><br>

<div>
  Number of divs in the service : {{ service?.divs?.length }}
</div>

答案 1 :(得分:0)

您无法在服务中使用Ubuntu 19.04,因为它没有模板。但是您可以在调用服务方法时从组件传递它:

@ViewChildren

当然,您需要修改服务:

export class MyComponent{

   @ViewChildren('focusable', {read: ElementRef}) focusableField: QueryList<ElementRef>;

   constructor(private fcs: FormControlService){}

   doSomething = (event) => { 
     this.fcs.setFocusDurchLink(event, this.focusableField);
   }
}

您可以在此处阅读有关export class FormControlService { setFocusDurchLink(event, focusableField: QueryList<ElementRef>) { this.dialogSektionen.forEach(element => { if (element.sektionTitel === event.target.innerHTML) { for (let i = 0; i < focusableField.length; i++) { ... } @ViewChildren@ViewChild@ContentChildren的更多信息:

https://medium.com/@tkssharma/understanding-viewchildren-viewchild-contentchildren-and-contentchild-b16c9e0358e