【问题标题】:Focus on element in ngFor is further off each item added to collection关注 ngFor 中的元素远离添加到集合中的每个项目
【发布时间】:2021-02-01 22:14:36
【问题描述】:

我使用@ViewChild 专注于在 Angular 的 for 循环中提出和回答的最后一个问题。这对于提出的第一个问题非常有效。但是,当我问第二个问题时,焦点不在元素上并且偏离了几个像素,然后再问一个问题会使偏移量加倍,依此类推。

我正在使用this question on SO 构建解决方案,我的解决方案代码如下:

HTML:

<div tabindex="1" #questionDiv class="faq-item" *ngFor="let faq of faqsAnswered">
    <div *ngIf="faq.question" class="ml-auto mr-3 col-lg-8 faq-user">
        {{faq.question}}
    </div>
    <div *ngIf="faq.answer" class="col-lg-8 ml-3 faq-response">
        {{faq.answer}}
        <p *ngIf="!feedbackGiven" class="mt-3">Was this answer helpful? <br /> <i class="fad fa-thumbs-up mr-3 text-success" (click)="provideFeedback(true)"></i> <i class="fad fa-thumbs-down text-danger" (click)="provideFeedback(false)"></i></p>
        <p *ngIf="feedbackGiven" class="mt-3">Thank you for your feedback!</p>
    </div>
</div>

CSS:

.faq-item {
    outline: none;
}

.faq-chat {
    max-height: 500px;
    overflow-x: hidden;
    overflow-y: auto;
}

还有打字稿:

export class FaqComponent implements OnInit {

  @ViewChildren('questionDiv') questionDivs: QueryList<ElementRef>;

  // tslint:disable-next-line: max-line-length
  constructor() { }

  // tslint:disable-next-line: use-lifecycle-interface
  ngAfterViewInit() {
    this.questionDivs.changes.subscribe(() => {
      if (this.questionDivs && this.questionDivs.last) {
        this.questionDivs.last.nativeElement.focus();
      }
    });
  }
}

【问题讨论】:

  • 你能创建一个带有复制的堆栈闪电战吗?根据这个部分代码很难回答:)
  • @MaciejWójcik 是对的,根据给定的信息无法回答您的问题。这听起来像是任何控件的边距或填充问题。

标签: javascript angular viewchild


【解决方案1】:

为了获得焦点,你的“div”应该有tabindex。至少是负面的,但它必须存在。

<div *ngFor="let item of elements" #questionDiv 
     tabindex="-1" class="list-item">
  {{item}}
</div>

您问题中的所有其他内容似乎都是有效的。这是我认为您一直在寻找的实现示例。

https://stackblitz.com/edit/focus-last-child

如果有一些我没有考虑或提出问题的特定条件,请随时 fork 或修改它

【讨论】:

    猜你喜欢
    • 2019-01-21
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2017-08-28
    相关资源
    最近更新 更多