2

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 :)

sandrina-p
  • 3,794
  • 8
  • 32
  • 60

1 Answers1

1

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".

Ankit Singh
  • 24,525
  • 11
  • 66
  • 89
  • thank you so much. Just one thing how do I apply required with *ngIf ? :/ -edit- i just found: [attr.hideBackButton]="someExpression" thnks :) – sandrina-p May 19 '16 at 13:19