【问题标题】:Angular ! and odd even角!和奇偶
【发布时间】:2021-07-19 15:35:16
【问题描述】:

这是任务: 您的任务是创建一个名为 TestComponent 的简单 Angular 组件,该组件由选择器 test-component 标识 组件必须有一个名为 inputData 的 Array 类型的输入属性。 如果没有输入数据(空或丢失),您必须在 id="noData" 的 div 中写入“无数据”。如果输入 鉴于此 div 不得出现在页面的 DOM 中。

如果给定输入,则必须将输入数组的元素写入单独的 div 中。 div必须是 具有 id="dataList" 的 div 的子级。如果任何给定字符串的长度是奇数,则文本的颜色应为红色。 如果是偶数,颜色应该是绿色的。

这就是我所做的:

import { Component, NgModule, EventEmitter, Output, Input } from '@angular/core';
 
@Component({
  selector: 'app-test-component',
  template: `
    <test-component>
        <div id="noData" *ngIf=!'inputData'>No data</div>
        <div id="dataList"></div>
    </test-component>
    <test-component>
        <div id="dataList" *ngIf='inputData'>
            <div *ngFor="let item of inputData; odd as isOdd; even as isEven;[ngClass]="{even: isEven, odd: isOdd}">
                <div>{{item}}</div>             
            </div>
        </div>
    </test-component>
  `,
   style: '.even {
    background-color: read;
      color: white;
    }

    .odd {
      background-color: gren;
      color: white;
    }'
})

export class TestComponent{
  @Input() inputData: Array<string>;
}

我的怀疑是尊重!在 ngIf 上,从 Dom 中取出元素和奇数、偶数。这些是我还没有的部分。可以给我一些更正吗?

【问题讨论】:

  • 我认为“偶数和奇数”是关于字符串的长度,而不是字符串的位置。是的,您可以使用[ngClass][style.color]。在 Angular 中,当我们使用 [property]="expresion" 时,“表达式”是任何简单的表达式。见:angular.io/guide/property-binding#binding-to-a-property。顺便说一句,你应该使用唯一的test-component作为选择器,而不是app-test-component,并且不要在组件中写标签“test-component”,你也可以使用*ngIf condition else template构造:angular.io/api/common/NgIf#description跨度>

标签: angular styles ngfor angular-ng-if


【解决方案1】:

您的bang/! 放错了位置。它应该在引号内。

<div id="noData" *ngIf="!inputData!>No data</div>

isOdd 或 isEven 的来源是什么?这是输入的一个字段还是您需要计算它?你可以做类似...

<div *ngFor="let item of inputData; index as index;" [ngClass]="{even: index % 2 === 0, odd: index % 2 !== 0}">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多