微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

专注于ngFor中的元素离添加到集合中的每个项目更远

如何解决专注于ngFor中的元素离添加到集合中的每个项目更远

我正在使用@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();
      }
    });
  }
}

解决方法

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

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

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

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

如果有一些具体情况我没有考虑或提出问题,请随意fork或修改

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。