0

I am learning angular2 and trying to implement a scenario where I have a text box in the page. Whenever I type any value to the text box, I want a cancel/remove text to appear to the right and selecting that should clear the entered value of the text box. In my html-

<md-input #productName name="productName" (keydown)="handleKeyDown($event)" type="text" placeholder="Start typing to select product types"></md-input>

I am not able to figure out how should I add and display the cancel text with cross icon upon typing the text. Can someone let me know how should I tweak my handleKeyDown function to achieve that.

1 Answer 1

2

You have to use *ngIf to show/hide that element and could use ngModel to clear your input.

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <br />

      <input [(ngModel)]="name" />
      <button *ngIf="name" (click)="name = ''">clear</button>
    </div>
  `,
})
export class App {
  name:string;
  constructor() { }
}

live demo: https://plnkr.co/edit/oXl4LEJK3sEc5HxXAaxe?p=preview

Sign up to request clarification or add additional context in comments.

9 Comments

I tried something like this. but the problem here is that the clear text displays even before entering any values.Its present in the DOM at the very beginning.I want to Clear text to display only when i enter something into text box but that's not happening. Instead I tried using *ngIf="!name.pristine" to display the text but that's not working.Any clue?
I can't understand your real problem i guess. would be great if you create a minimal plunker to reproduce it.
In your example, the default value of the textbox is set to 'Angular2'. Whereas in my case, i do not have any default value set but still the cancel text is present in the DOM. I want to display this cancel/clear text only when I enter any value in textbox.Let me know if this is still not clear, I will add plunker.
updated the plunker, now there isn't a default value. startingpoint is whithout clear-button?!
Yep. Clear button should not be added into the DOM until we type any value in the textbox.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.