1

I built a feature adding "and zombies" to book names of choice, using basic angular.

         <input type="text" ng-model="bookname" onclick="zombies()"> 
            <h1> {{bookname}} </h1> 

I want the "and zombies" (and the text inserted in the input) to be displayed only when there's text inside the input.

I tries this for starts, just to call the angular using JS and it doesn't work.

      <script>
    function zombies() {
    document.getElementsByTagName("h1").innerHTML = "{{}}" + "and zombies";
    };
    </script>

How do I display the text when there's text inside the input? (please go easy on me, I'm studying alone and you all started as juniors)

3 Answers3

1

You Just need to add the condition which checks the value of bookname and display the static content with your name.

Like this -

<input type="text" [(ngModel)]="bookname" (click)="zombies()"> 
<h1> {{bookname}} <span *ngIf='bookname'>and zombies</span> </h1> 
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
0

You can use a condition here.

<input type="text" [(ngModel)]="bookname" onclick="zombies()"> 
<h1 *ngIf="bookname"> {{bookname}} and zombies</h1> 

Or if you want to use javascript:

<input type="text" ng-model="bookname" onclick="zombies()"> 
<h1 id="txtheading"></h1> 

function zombies() {
    var heading_value = document.getElementById("txtheading").value;
    document.getElementById("txtheading").innerHTML = heading_value  + " and zombies";
};
Prachi
  • 3,478
  • 17
  • 34
0

Easiest Solution you don't need onclick function ng-model will work itself.

AngularJs:

<input type="text" ng-model="bookname">
<h1>{{(bookname)? bookname+' and zombies' : bookname}}</h1>

Angular 2/4/5/6:

<input type="text" [(ngModel)]="bookname">
<h1>{{(bookname)? bookname+' and zombies' : bookname}}</h1>
Sanoj_V
  • 2,936
  • 1
  • 12
  • 28