sandrina-p
sandrina-p

Reputation: 4160

Angular2: [(ngModel)] with ion-select - show div depending on select value

I'm working with ionic2 and angular2 with javascript (not typescript) I have 2 inputs: text and select. I want to hide input text if select.val() == 'more'. How do I do that?

This is the code i have:

        <ion-item class="sq-p-input-price" *ngIf="typePriceMore()">
            <ion-label for="price" class="sr-only">Price</ion-label>
            <ion-input id="price" type="number" value="" placeholder="Price" required></ion-input>
        </ion-item>

        <ion-item class="sq-p-input-type">
            <ion-label class="sr-only" for="type">Tipo</ion-label>
            <ion-select [(ngModel)]="priceTypeModel" id="type" required>
                <ion-option *ngFor="#option of priceType"  value="{{option.value}}">{{option.key}}</ion-option>
            </ion-select>
        </ion-item>

The array on #option is:

    this.priceType = [
        {
            key: 'fixo',
            value: 'fix'
        },
        {
            key: '/hora',
            value: 'hourly'
        },
        {
            key: 'Preciso mais informação',
            value: 'more'
        },
    ]

Besides that there are 2 thinks more I'm having difficult to accomplish:

1 - Set a initial value to the select. Using selected isn't working than causes my being always empty when I load the page.

2 - When the input.text (price) is hidden, to remove the attribute "required".

Thanks :)

Upvotes: 2

Views: 2797

Answers (1)

Ankit Singh
Ankit Singh

Reputation: 24945

To set a initial value on an ngModel, you should define it in the constructor()

constructor(){
  priceTypeModel = 'more';
}

To hide an element there are two options

  1. [hidden] attribute (if true, sets display:none on the element, stays in DOM)

<ion-item class="sq-p-input-price" [hidden]="priceTypeModel === 'more'">

    <ion-label for="price" class="sr-only">Price</ion-label>
    <ion-input id="price" type="number" value="" placeholder="Price"></ion-input>
</ion-item>
  1. *ngIf directive (if false, removes element from the DOM)

<ion-item class="sq-p-input-price" *ngIf="priceTypeModel !== 'more'">

    <ion-label for="price" class="sr-only">Price</ion-label>
    <ion-input id="price" type="number" value="" placeholder="Price"></ion-input>
</ion-item>

You should use *ngIf in the case below, which removes the element from DOM, so no more required validation

2 - When the input.text (price) is hidden, to remove the attribute "required".

Upvotes: 1

Related Questions