0

This is a component that reuse in a form for registering item. here i have some types. like for a phone number there are work, home, mobile types. value for 'data' are taken from service file.
type.component.html

  <ng-container *ngIf="types">
    <select [ngModel]="selectedIndex" (ngModelChange)="valueChanged($event)">
      <option *ngFor="let type of types" [value]="type.code">
        {{ type.code }}
      </option>
    </select>
  </ng-container>
  <ng-container *ngIf="data">
    <select [ngModel]="selectedIndex" (ngModelChange)="valueChanged($event)">
      <option *ngFor="let item of data" [value]="item.id">
        {{ item.name }}
      </option>
    </select>
  </ng-container>

type.component.ts

@Input()
  get data(): User[] {
    return this._data;
  }

@Input()
 get types(): Type[] {
   return this._types;
 }

 set types(value: Type[]) {
   this._types = value;
 }

 set data(value: User[]) {
   this._data = value;
   this.userservice.getUserList();
 }

 private _types: Type[] = [];
 private _data: User[] = [];

in form.component.html I reuse above type.component.html as my-type. when i use <my-type [data]="userData"></my-type> it should call second if condition. And <my-type [types]="typeData"></my-type> it should call first if condition.
now both of conditions are called and display two components. when I use *ngSwitch it doesn't work for data.
How can I solve this?

  • 1
    I think the problem is that your `*ngIf` condition always evaluates to `true` because your default values are empty arrays. try initializing `_types` and `_data` to `undefined` instead of `[]` and see if it works. – BizzyBob Feb 09 '23 at 18:29
  • You're question isn't very clear. In your component though, you are setting both `_types` and `_data` to empty arrays, so `*ngIf="data"` will never be false. Maybe try `*ngIf="data.length"` instead? – peinearydevelopment Feb 09 '23 at 18:30
  • Your `@Input`s should be on your setters – Pieterjan Feb 09 '23 at 20:25

0 Answers0