【问题标题】:How to choose HTML according to the value while using ngFor in angular4? [duplicate]在angular4中使用ngFor时如何根据值选择HTML? [复制]
【发布时间】:2018-02-09 01:04:45
【问题描述】:

我是 Angular 新手,假设我有一个这样的值数组

domElement:Array<boolean>=[true,false,false,false,false,true,true,true];

在使用 ngFor 时,我希望为真值使用不同的 html,为假值使用不同的 html,我遵循了这个 blog 并实现了这个,但它不起作用

即。

     <div *ngFor="let n of domElement; let i=index">   

<div *ngFor="let n of num; let i=index">

    <ng-template *ngIf="n; then gotValue else noValue"></ng-template>

    <ng-template #noValue>
        <div class="alert alert-warning">
            no value found - dummy element for no record !!!
        </div>
    </ng-template>
    <ng-template #gotValue>
        <div class="alert alert-success">
            got values !!!
        </div>
    </ng-template>
</div>

【问题讨论】:

    标签: angular ngfor angular-ng-if


    【解决方案1】:
    1. 如果您只需要两个特定案例场景的不同代码,那么您必须使用。 *ngIf / else 不是 *ngIf / then / elseExplanation here

    <div *ngFor="let n of num"> <template1 *ngIf="n%2 === 0; else other_content"></template1> <template2 #other_content></template2> </div>

    1. 如果您的代码没有改变,而唯一改变的是样式,则最好使用一个通用组件并通过 ng 类指令 进行样式替换。

    &lt;some-element [ngClass]="{'first': true, 'second': true, 'third': false}"&gt;...&lt;/some-element&gt;

    【讨论】:

      【解决方案2】:

      我猜你定义了两个同名的不同块在你的代码中没有#gotValue块试试这个:

      <div *ngFor="let n of domElement">
          <ng-template *ngIf="n; then noValue else gotValue"></ng-template>
          <ng-template #noValue>
              <div class="alert alert-warning">
                  no value found - dummy element for no record !!!
              </div>
          </ng-template>
          <ng-template #gotValue>
              <div class="alert alert-success">
                  got values !!!
              </div>
          </ng-template>
      </div>
      

      【讨论】:

      • 我尝试实现这一点,但无论值是什么,我总是显示 ,请查看我更新的问题,谢谢
      • 如果我的新实现对您不起作用,请与我们分享组件代码。这可能是导致 n 等于“未定义”的原因,这意味着 if 子句会自动将您重定向到 false 块。
      【解决方案3】:

      这是你要找的吗?

      <div *ngFor="let n of num">
          <template1 *ngIf="n%2 === 0"></template1>
          <template2 *ngIf="n%2 !== 0"></template2>
      </div>
      

      【讨论】:

        【解决方案4】:
        <div *ngFor="let n of num; let i=index">
        <div *ngIf="n%2===0;else gotValue"></div>
            <div class="alert alert-warning">
                no value found - dummy element for no record !!!
            </div>
        <ng-template #gotValue>
            <div class="alert alert-success">
                got values !!!
            </div>
        </ng-template>
        

        您不需要 noValue ng-template。这对我有用。希望对您有所帮助。

        【讨论】:

          猜你喜欢
          • 2017-09-01
          • 2019-02-06
          • 2018-02-09
          • 2018-10-16
          • 2019-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-24
          相关资源
          最近更新 更多