简体   繁体   English

Angular | 如何使用 ngFor 将样式设置为动态 id?

[英]Angular | How to set a style to a dynamic id with ngFor?

I have this dynamic id and I need to set a style for it, but how do I do it?我有这个动态 id,我需要为它设置一个样式,但是我该怎么做呢? Is there a method?有方法吗?

component.html组件.html

<tr *ngFor="let channel of channels | slice: (page-1) * pageSize : page * pageSize>
//Other code...
<ng-container *ngFor="let flow of flows">
            <td>
              <div id="flow_{{channel.id}}_{{flow.id}}" style="display:none">
                <i class="bi bi-check-lg"></i>
              </div>
            </td>
 </ng-container>
</tr>

I tried doing this in my component.ts but it doesn't work, it doesn't iterate the values correctly.我尝试在我的 component.ts 中这样做,但它不起作用,它没有正确地迭代值。

 idChannel: any;
  idFlow: any;
  check() {
    this.channelService.getChannels().subscribe(response => {
      this.channels = response.result
      for (var i = 0; i < response.result.length; i++) {
        this.idChannel = response.result[i]['id']
        this.flowService.getFlows().subscribe(response => {
          this.flows = response.result
          for (var i = 0; i < response.result.length; i++) {
            this.idFlow = response.result[i]['id']
          }
          document.getElementById('flow_' + this.idChannel + '_' + this.idFlow).style.display = 'show';
        })
      }
    })
  }

Is there another way to do this?还有另一种方法吗? In the component or maybe directly in the html with some directive?在组件中或者直接在 html 中使用一些指令?

Here's an example from one of my current projects:这是我当前项目之一的示例:

<input type="text" 
  [ngClass]="ingredient.drugName == 'DRUG NAME NOT FOUND'
    ? 'text-danger fw-bold'
    : 'drug-found'"
  name="DrugName{{index}}"
      disabled
      pattern="/^(?!.*DRUG NAME NOT FOUND.*).*$/g"
      class="form-control"
      [(ngModel)]="ingredient.drugName">

So what is happening here is that first it checks the conditional:所以这里发生的是首先它检查条件:

ingredient.drugName == 'DRUG NAME NOT FOUND'

if ingredient.drugName is DRUG NAME NOT FOUND , it will apply the text-danger and fw-bold css classes to the field, and the text will be red and bold.如果 ingredient.drugName 是DRUG NAME NOT FOUND ,它会将text-dangerfw-bold css 类应用于该字段,并且文本将为红色和粗体。 If not, then it applies the drug class, and it will do some other stuff that isn't important here.如果没有,那么它会应用drug class,它会做一些其他在这里不重要的事情。 The point is that you can conditionally apply css classes to an element.关键是您可以有条件地将 css 类应用于元素。

Here is a good article that goes over not only the simple conditionals, but also goes into some more complex examples: https://www.freecodecamp.org/news/angular-ngclass-example/这是一篇很好的文章,它不仅介绍了简单的条件,还介绍了一些更复杂的示例: https://www.freecodecamp.org/news/angular-ngclass-example/

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

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