Show as many items as selected option value with *ngFor - Angular2

715 Views Asked by At

I am using Angular2 but quite new at it as well.

I need to solve this problem out. I have a select with option values from 1 to 4.

According to the option chosen i would like to show as many items as the select option value shows like in the images below.

room number chosen = 1 - 1 item shown

room number chosen = 2 - 2 items shown

Any ideas about how it can be done?

3

There are 3 best solutions below

0
On

As stated here: How to apply filters to *ngFor

You can simply apply a filter on the element. e.g.

<p *ngFor="let feature of content?.keyFeatures | slice:1:maxNumberItems">
   {{ feature.description }}
</p>
0
On

You can use template variable, i.e :

    <select id="timesSelect" #timesSelect>
      <option *ngFor="let no of availableRoomsNoCollection" 
      [value]="no">{{no}}</option>
    </select>

    <div *ngFor="let no of collectionFrom(#timesSelect.value)">
       <!--Show items-->
    </div>

Where:

availableRoomsNoCollection = this.collectionFrom(availableRoomsNo);

collectionFrom(n: number): number[] {
   return Array(n).fill().map((x,i)=>i + 1); // [1,2,3,4,..., n]
}
0
On

I followed the suggestions of Jamie Torres. Now it looks working! The only problem now is that when i change too quickly the values of the select "father" (#changRoomNum), it retrieves this error

"Expression has changed after it was checked. Previous value: ''. Current value: '[object Object]'."

this is my code:

search.component.html

<div class="search">
<div class="container">
  <h3>
   Search your hotel
  </h3>
  <form [formGroup]="myForm" autocomplete="off" novalidate>


    <div class="form-field">
      <div class="col-md-12">
        <label for="">Insert your destination</label>
        <input type="text" class="form-control" formControlName="destination">
        <!-- INSERISCO IL MESSAGGIO DI VALIDAZIONE -->
        <div *ngIf="myForm.controls.destination.errors && (myForm.controls.destination?.dirty || myForm.controls.destination?.touched)">
          <div class="alert alert-danger" *ngIf="myForm.controls.destination.errors?.required">This field is mandatory</div>
        </div>
      </div> 
    </div>


    <div class="form-field">
      <div class="col-md-6">
        <label for="">Arrival</label>
        <input type="date" class="form-control" formControlName="arrival">
        <div *ngIf="myForm.controls.arrival.errors && (myForm.controls.arrival?.dirty || myForm.controls.arrival?.touched)">
          <div class="alert alert-danger" *ngIf="myForm.controls.arrival.errors?.required">Fill properly the field</div>
        </div>
      </div>
      <div class="col-md-6">
        <label for="">Departure</label>
        <input type="date" class="form-control" formControlName="departure">
        <div *ngIf="myForm.controls.departure.errors && (myForm.controls.departure?.dirty || myForm.controls.departure?.touched)">
          <div class="alert alert-danger" *ngIf="myForm.controls.departure.errors?.required">Fill properly the field</div>
        </div>
      </div>    
    </div>

    <div class="form-field">
      <div class="col-md-3">
        <label for="">Rooms Num.</label>
        <select #t (change)="changeRoom(t.value)" [(ngModel)]="roomsNums" [ngModelOptions]="{standalone: true}" class="form-control" name="" id="changRoomNum">
          <option [selected]="selectedRoom==1" *ngFor="let room of rooms" [value]="room.value">
              {{room.value}}
          </option>
        </select>
      </div>
      <div class="col-md-3">
        <h4>ROOMS N. {{t.value}}</h4>
       </div>


       <div class="col-md-6" *ngFor="let room of rooms | slice:0:roomsNums">

         <div class="col-md-6">
          <label for="">Adults</label>
          <select class="form-control" name="" id="">
              <option selected value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
          </select>
        </div>

        <div class="col-md-6">
          <label for="">Children</label>
         <select #childrenNum (change)="callType(childrenNum.value)"  class="form-control" name="" id="">
              <option *ngFor="let child of children" [value]="child.value">
                  {{child.value}}
              </option>
          </select>

          <div *ngFor="let child of children | slice:0:childrenNum.value">
            <select name="" id="">
            <option value=1>1</option>
             <option value=2>2</option>
              <option value=3>3</option>
               <option value=4>4</option>
                <option value=5>5</option>
                 <option value=6>6</option>
                  <option value=7>7</option>
                   <option value=8>8</option>
                    <option value=9>9</option>
                     <option value=10>10</option>
                      <option value=11>11</option>
                       <option value=12>12</option>
              </select>

          </div> 
        </div>

      </div>


    </div>


    <div class="form-field">
        <div class="col-md-3  col-md-offset-6"> 
          <button (click)="reset()" class="btn btn-danger" type="submit">Reset</button>
        </div>
         <div class="col-md-3"> 
          <button routerLink="/heroes" [disabled]="!myForm.valid" class="btn btn-primary"  type="submit">Search</button>
        </div>
    </div>
  </form>
</div>
</div>

search.component.ts

import { Component, OnInit, OnChanges } from '@angular/core';
import {FormGroup, FormControl, Validators} from '@angular/forms';

@Component({
  selector: 'search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
  photo= 'http://wallup.net/wp-content/uploads/2016/01/178625-nature-sea-Bora_Bora.jpg'
  myForm: FormGroup;


  // ISTANZIO I MIEI CAMPI DI VALIDAZIONE DENTRO IL CONSTRUCTOR
  constructor() { 
    this.myForm = new FormGroup({
      destination: new FormControl('', [
        Validators.required,
        Validators.pattern('[A-Za-z]+')
      ]),

      arrival: new FormControl('',[
          Validators.required
          //Validators.pattern('/^\d{1,2}\.\d{1,2}\.\d{4}$/')
      ]),
      departure: new FormControl('',[
          Validators.required,
          //Validators.pattern('/^\d{1,2}\.\d{1,2}\.\d{4}$/')
      ]),

    });
  }

  reset(){
    this.myForm.reset();
  }

  callType(value){
    console.log(value);
    return value;
  }
  changeRoom(value){
    console.log(value);
    return value;
  }

  rooms = [
    {value: '1'},
    {value: '2'},
    {value: '3'},
    {value: '4'}
  ];

  children = [
    {value: '1'},
    {value: '2'},
    {value: '3'},
    {value: '4'}
  ];

  selectedRoom = 1;

  ngOnInit() {

  }

}

Plus it always shows me the last value of select father by default, which means to say (4 rooms)