Icon not displayed inside input line in Ionic 3

2019-03-07 00:41发布

问题:

I have the following code in my Ionic 3 project.

<ion-item>
  <ion-icon name="person" item-start></ion-icon>
  <ion-label floating>Email</ion-label>
  <ion-input type="email" name="email" [(ngModel)]="registerCredentials.email" required></ion-input>
</ion-item>

This gives me the following result.

The icon in outside of the input line. Who to get it inside by keeping my Label floating.

回答1:

You can fix that by placing the icon inside of the label, like this:

<ion-item>      
  <ion-label floating>
    <ion-icon name="person" item-start></ion-icon> // <--- Here!
    Email
  </ion-label>
  <ion-input type="email" name="email" [(ngModel)]="registerCredentials.email" required></ion-input>
</ion-item>

Working plunker

EDIT

If I do that the Icon and Label both are floating when the field is selected. Only the label should float up.

In order to prevent that, you can add the following style rule:

ion-item.input-has-focus ion-label[floating] ion-icon,
ion-item.input-has-value ion-label[floating] ion-icon {
    display: none;
}

That way the icon will be shown only when the label is not floating.

EDIT II

It's working they way you want it to work but my solution will be the Icon should remain visible in the box and the label will float. Is that possible?

You could add a few style rules to do that. The key would be to place the icon outside the ion-label, and set its position to be an absolute value. Please take a look at this new updated plunker

The result would be like this:

html

  <ion-item>      
    <ion-icon name="person" item-start></ion-icon>
    <ion-label floating>
      Email
    </ion-label>
    <ion-input type="email" name="email" required></ion-input>
  </ion-item>

scss

ion-item {
  position: relative;
}

ion-item.item-label-floating .text-input {
  margin-left: 32px;
  width: calc(100% - 32px);
}

ion-item.item-input ion-icon {
  display: flex;
  align-items: flex-end;
  position: absolute;
  bottom: 0;
  left: 44px;
  color: #7f7f7f;
  font-size: 24px;
  min-width: 0 !important;
  text-align: left !important;
}


ion-item.item-input ion-label[floating] {
      padding-left: 32px;
}

ion-item.input-has-focus ion-label[floating],
ion-item.input-has-value ion-label[floating] {
  pading-left: 0;
  transform: translate3d(-25.6px, 0, 0) scale(0.8); /* 25.6 is equal to 32 * 0.8 (the scale factor) */
}