Sep 13, 2019 in Angular
Q: Angular Error Fixing

1 Answer

0 votes
Sep 13, 2019

Angular Error Fixing

Here, "component.html" file contains the following code:

  1. <div class="container">  
  2.   <div class="row">  
  3.  <div class="col-xs-12">  
  4.    <h2>My Servers</h2>  
  5.    <button class="btn btn-primary" (click)="OnAddServer()">Add Server</button>  
  6.  <br><br>  
  7.   
  8.  <ul class="list-group">  
  9.    <li  
  10.    class="list-group-item "  
  11.    *ngFor="let server of servers; let i = index"  
  12.    (click)="onRemoveServer(i)">{{ server }}  
  13.    </li>  
  14.  </ul> </div>  
  15.  </div>  

component.ts file:

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'testing-app';  
  10.   servers;  
  11.   
  12.   OnAddServer() {  
  13.     this.servers.push('Another Server Added');  
  14.   }  
  15.   
  16.   onRemoveServer(id: number) {  
  17.     const position = id + 1;  
  18.     this.servers.splice(position, 1);  
  19.   }  
  20. }  

See the output:

Now, if you click on the "Add Servers" button, it will not add any server. Open the browser console to see the error type.

Angular Error Fixing

Sep 13, 2019

You can see that it is showing "push" property undefined. Here, you get some useful information about errors.

Let's check component.ts file:

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'testing-app';  
  10.   servers;  
  11.   
  12.   OnAddServer() {  
  13.     this.servers.push('Another Server Added');  
  14.   }  
  15.   
  16.   onRemoveServer(id: number) {  
  17.     const position = id + 1;  
  18.     this.servers.splice(position, 1);  
  19.   }  
  20. }  

Here, we have declared servers but it is not initialized. So, we set it to be in array format to keep newly created servers. So, change it to:

  1. servers= [];  

Change the component.ts:

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'testing-app';  
  10.   servers = [];  
  11.   
  12.   OnAddServer() {  
  13.     this.servers.push('Another Server Added');  
  14.   }  
  15.   
  16.   onRemoveServer(id: number) {  
  17.     const position = id + 1;  
  18.     this.servers.splice(position, 1);  
  19.   }  
  20. }  

Related questions

0 votes
Sep 13, 2019 in Angular
0 votes
Sep 13, 2019 in Angular
...