【发布时间】:2021-12-27 16:11:58
【问题描述】:
我的问题来自一种情况(我已经解决了它,但我正在寻找好的做法)。我有一个自动从 API 获取数组的输入。然后使用此数组运行*ngFor 以显示选项并关注第一个选项,但这是我的问题:我必须使用 setTimeout 以便 angular 获取呈现的选项,否则我会得到未定义的选项。我一直在使用它,但我知道使用 setTimeout 不好,因为要重新观察所有状态,我的问题是最好的方法是什么?是用 rxjs 吗?
父组件
@Component({
template:`
<generic-child-component></child-component>
`
})
export class ParentComponent implements OnInit{
@ViewChild(ChildGenericComponent)child: ChildGenericComponent
delaySubject: Subject<string> = new Subject();
contructor (private apiService: ApiService){}
ngOnInit(){
this.delaySubject.pipe(
debounceTime(2500),
).subscribe(query=>{
this.apiService.get(query).subscribe(fetchedData=>{
this.child.fetchedOptions = fetchedData
//Here I want to put a focus in the first Object
//but i need to make a setTimeout to get the rendered option in the child component
setTimeout(() => {
this.child.optionsInputs.first.nativeElement.focus() //If this its outside this setTimeout the child.optionsInputs = undefined
})
})
})
}
ngAfterViewInit(): void {
this.child.form.controls['filter'].subscribe(query=>this.delaySubject.next(query))
}
}
子组件
import { Component, ElementRef, QueryList, ViewChildren } from "@angular/core";
import { FormBuilder, FormGroup} from "@angular/forms";
@Component({
selector:'generic-child-component',
template:`
<form [formGroup]="form">
<input [formControlName]="'filter'" type="text">
</form>
<div *ngFor="let option of fetchedOptions">
<input #optionsInputs >
{{option}}
</div>
`
})
export class GenericDelayComponent {
@ViewChildren('optionsInputs')optionsInputs:QueryList<ElementRef>
constructor(private fBuilder:FormBuilder){}
fetchedOptions=[]
form: FormGroup = this.fBuilder.group({
filter:[null]
})
}
【问题讨论】:
-
setTimeout 在这种情况下绝不是一个好主意 - 如果 API 需要更长的时间来处理请求/回答会发生什么?你在 component.ts 中使用
subscribe()吗? -
初始化数组为空数组。因此, *ngFor 不会抛出任何错误。而不是使用 setTimeout 使用 JeffryHouser 提到的选项 1。
-
@iLuvLogix 我在获取数据后使用 setTimeout。我会尝试提供一个示例代码。
标签: angular rxjs settimeout