【问题标题】:how to loop through a div which contains multiple div using angular2如何使用angular2遍历包含多个div的div
【发布时间】:2023-03-30 23:54:01
【问题描述】:

我有一个要求,用户将被问到从 1 到 5 的一系列问题,并且这些问题将循环出现,例如用户首先回答第一个问题,然后单击下一个问题旁边,他也可以转到上一个问题。 当问题结束时,他将提交。

我正在尝试遍历包含多个 div 螺母的 div 我在使用角度 2 中的视图子时遇到错误

虚拟数据

 <div #message>
           <div>
               Here
           </div>
           <div>
               Here again
           </div>
       </div>
    </div>


<div *ngFor = "let in of input">
    {{in}}
</div>


@ViewChild('message') input :ElementRef;

控制台日志

XCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/questioncomponent/question.component.html:14:5 caused by: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
    at new Error (native)
    at NgFor.ngOnChanges (http://localhost:3000/node_modules/@angular/common/bundles/common.umd.js:1646:31) [angular]
    at Wrapper_NgFor.ngDoCheck (/CommonModule/NgFor/wrapper.ngfactory.js:49:20) [angular]
    at DebugAppView.View_QuestionComponent0.detectChangesInternal (/AppModule/QuestionComponent/component.ngfactory.js:102:20) [angular]
    at DebugAppView.AppView.detectChanges 

【问题讨论】:

  • 你能确定你是否在*ngFor中使用数组
  • 您的输入是一个对象。您必须将每个 div 推入一个数组并在 ngFor 中使用它
  • 你能解释一下我是 Angular 的新手吗
  • 你能显示你的 JSON
  • @M Balajivaishnav div 现在将被硬编码,带有问题和答案

标签: angular ngfor viewchild


【解决方案1】:

以下代码应该可以工作。 For loops 需要输入一个数组。但是,如果没有比使用ElementRef 更好的方法来解决您的问题,您应该重新考虑。见the API

你的模板

<div #message>
    <div>
        Here
     </div>
     <div>
        Here again
     </div>
   </div>
</div>

在你的组件中

@ViewChild("message") message:any;

ngAfterViewInit() {
  for (let div of this.message.nativeElement.children) {
        console.log(div.textContent);
    }
}

【讨论】:

  • 但是我们如何遍历 div 这是我想要更改的虚拟数据添加一个隐藏类并在用户单击按钮时显示下一个 div
  • 像一个问卷调查
  • 每个 Angular2 教程的第一章都传达了您的要求。基本上,您只需要一些带有 ngIf 的 div 元素和两个跳过问卷页面的按钮。您真的应该阅读 Angular2 的基本技术。
  • 我可以使用 ngIf ,但它有 10 个这样的 div,还有其他使用循环的方法我想尝试一下
  • 如果没有看到你到目前为止所得到的,很难说。
猜你喜欢
  • 2021-09-05
  • 1970-01-01
  • 2014-05-08
  • 2012-04-13
  • 1970-01-01
  • 2022-08-05
  • 2017-01-12
  • 2018-11-05
  • 1970-01-01
相关资源
最近更新 更多