3

this is the task: Your task is to create a simple Angular Component named TestComponent identified by the selector test-component The component must have an input property of type Array named inputData. If there is no input data (empty or missing) you have to write "No data" in a div with id="noData". If the input is given this div must not be present in the DOM of the page.

If the input is given, you have to write the elements of the input array into separate divs. The divs have to be children of a div with id="dataList". If the length of any given string is odd, the color of the text should be red. If its even, the color should be green.

This is what I have done:

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>;
}

My doubts are respecting the ! on the ngIf, taking out of the Dom the element and the odd, even thing. Those are the parts I don´t have yet. Can you please give me some corrections?

Jhon Hernández
  • 293
  • 5
  • 20
  • I think that the "even and odd" is about the length of the string, not the position of the string. And yes, you can use `[ngClass]` or `[style.color]`. In angular, when we use `[property]="expresion"` "expresion" is any simple expresion. see:https://angular.io/guide/property-binding#binding-to-a-property. BTW, you should use as selector unique `test-component`, not app-test-component, and don't write in the component the tags "test-component", you can use also the `*ngIf condition else template` construction:https://angular.io/api/common/NgIf#description – Eliseo Jul 19 '21 at 16:12

1 Answers1

2

Your bang/! is in the wrong spot. It should be within the quotes.

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

What is the source of the isOdd or isEven? Is that a field of the input or do you need to compute that? You could do something like...

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

Lev Chlumov
  • 126
  • 1
  • 2