简体   繁体   English

检查 ngIf 数组组件角度

[英]check with ngIf an array component angular

When you check just for variable then this code is enough当您只检查变量时,此代码就足够了

<div class="someComponent" *ngIf="someVariable">

But how can I use a specific component of array instead of variable?但是如何使用数组的特定组件而不是变量? for example I want to check for array component someArray[] using idVar someArray[idVar] ?例如,我想使用 idVar someArray[idVar]检查数组组件someArray[] someArray[idVar] How can I put this inside ngIf?我怎样才能把它放在 ngIf 中?

I have in my ts file someArray: Boolean[];我的 ts 文件中有 someArray: Boolean[];

then in my template I have some loop where I constract divs with *ngIf="someArray[idVar]" because someArray has actual arguments for this moment there was error Cannot read property '1' of undefined then I wrapped everything in <ng-container *ngIf="someArray"> so when I load the page , because someArray do not exists everything works fine.然后在我的模板中,我有一些循环,我用*ngIf="someArray[idVar]"构造 div,因为 someArray 此刻有实际参数,出现错误Cannot read property '1' of undefined然后我将所有内容都包装在 <ng-container 中*ngIf="someArray"> 所以当我加载页面时,因为 someArray 不存在所以一切正常。 but then I have button on press I transfer 1 to ts file and put 'true' value to someArray[1].但是然后我按下按钮我将 1 传输到 ts 文件并将“真”值放入 someArray[1]。 When I do so script goes on error Cannot read property '1' of undefined当我这样做时,脚本出现错误Cannot read property '1' of undefined

I guess you are using the *ngFor directive.我猜你正在使用 *ngFor 指令。 You can write let i = index inside the *ngFor like *ngFor ="let element of elements; let i = index" in order to have access on the iterator of the element.您可以像*ngFor ="let element of elements; let i = index"一样在 *ngFor 中编写 let i = index 以访问元素的迭代器。 With this logic you can achieve what you want.有了这个逻辑,你就可以实现你想要的。

If this doesn't work for you, you have to be more accurate about the idVar.如果这对您不起作用,您必须更准确地了解 idVar。 What is its scope?它的范围是什么? Is it somehow defined in the template or can you retrieve it by using a function inside the .ts file?它是在模板中以某种方式定义的,还是可以通过使用 .ts 文件中的函数来检索它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM