Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngIf on input value

I have field which get the input of the user and according to it the below element will show what has been written

 <label>message</label>
 <input type="text" name="name" [(ngModel)]="person.message"class="form-control">

 <label class="label">you've written this </label>
 <input type="text" name="name" disabled value="{{message}}" class="form-control">

this code works fine but I want to assign a condition to the shown value which is somthing like this: *ngIf=person.message!=null?{{message}}":'write'

which means if the input filed is not null show what is written else show the word write

like image 721
eze Avatar asked Apr 11 '20 18:04

eze


People also ask

What is* in* ngIf in Angular?

Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element. The *ngIf directive is most commonly used to conditionally show an inline template, as seen in the following example. The default else template is blank.

How does* ngIf work?

The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.


2 Answers

You can use ternary operator within {{...}}

 <input type="text" name="name" disabled value="{{person.message!=null ? message : 'write'}}" class="form-control">

Or set value as a property with ternary operator.

<input type="text" name="name" disabled [value]="person.message!=null ? message : 'write'" class="form-control">
like image 88
Pranav C Balan Avatar answered Oct 17 '22 02:10

Pranav C Balan


Just check if the value exist or not else assign the default valus usng OR operator.

<label>message</label>
     <input type="text" name="name" [(ngModel)]="person.message" class="form-control">

     <label class="label">you've written this </label>
     <input type="text" name="name" disabled [value]="person.message ? message : 'write'" class="form-control">
like image 1
Jasdeep Singh Avatar answered Oct 17 '22 03:10

Jasdeep Singh