0

This is my input field

<input 
(keyup.enter)="save()" 
(focusout)="save()" 
class="editinput custom_story_input" 
type="text" 
placeholder="Create a new one"
id="tbtfeild"
value="" [(ngModel)]="childTaskmodel.childtitle"
#childtitle="ngModel"
name="childtitle" />

From the above input field, I don't have any problem with enter if the field is empty it shows the error message

Coming to focus out it should only work if there is any data present in the input field how can i do this..?

i want something like this:

  <input *ngIf (focusout)="childtitle.val != '' ? save() : '' " >
Mr world wide
  • 4,696
  • 7
  • 43
  • 97
  • Instead of handling `(keyup.enter)` and `(focusout)`, you could handle `(change)`. – ConnorsFan Feb 09 '18 at 15:05
  • can you provide any reference to that, i use to do that in javascript, but i don't know how to handle in Angular 4 – Mr world wide Feb 09 '18 at 15:06
  • Take a look at [this question](https://stackoverflow.com/q/44840735/1009922). Replace `(keyup.enter)="save()"` with `(change)="save()"`. – ConnorsFan Feb 09 '18 at 15:08
  • @ConnorsFan not to be a pain in *where tou think*, but change is an event that is bound to `select` attributes. You should instead use `(input)` –  Feb 09 '18 at 15:09
  • @trichetriche - `(input)` would be the equivalent of `(ngModelChange)`. `(change)` is what the OP wants to do in his code. See [this stackblitz](https://stackblitz.com/edit/angular-vpaznv). – ConnorsFan Feb 09 '18 at 15:13

2 Answers2

2

Welll you can do that :

<input [(ngModel)]="childtitle" (focusout)="childtitle ? save() : null">

test it : unless your input has a value, it won't work.

EDIT Explanation :

you first bind your variable to the input with [(ngModel)]="childtitle" : this allows you to let angular know that he has to watch for changes on that variable.

Next, you bind an HTML event to this input, with (focusout)="childtitle ? save() : null". As a value, you write a ternary operator : this is a one-liner for a if ... else ... condition. In that ternary, you state that if this input has a value (this is a truthy value, a Javascript concept, you will find more on the internet), then you can run the function. If not, then you just run null, which ... Does nothing.

  • It worked like a magic thanks for the help. I will accept in 5mins, can you please explain the answer little bit. – Mr world wide Feb 09 '18 at 15:14
  • 1
    Hi, sorry I wasn't available this weekend, I explained my answer in an edit, feel free to see it –  Feb 12 '18 at 07:32
1

Inside your save() function, check your model childTaskmodel.childtitle. If it's empty, don't continue. If you want different behaviour for your keyup.enter and focusout, just create two methods inside controller.

Petr Adam
  • 1,425
  • 11
  • 23