1

I am a newbie in Angular, I create an array but I have problem to display it.

When I display the array item it is blank.

write.component.html:


    <div class="data">
        <li> Name: <input type="text" [(ngModel)]="name" placeholder="Please enter Name" ></li>
        <li> Age:<input type="text" [(ngModel)]="age" placeholder="Please enter Age" class="age"></li>
        <li>College:<input type="text" [(ngModel)]="college" placeholder="Please enter College" ></li>
        </div>

    <h2>Student</h2>
    <ul class="details">
      <li>
        <span class="badge" *ngFor="let student of students">  // display array item
          {{student.name}}{{student.age}}{{student.college}}</span>
      </li>
    </ul>

.ts

export class WriteComponent implements OnInit {
  name : string;
  age : number;
  college : string;

students : Array<any>; // declare array

}

write-service.ts

import { Injectable } from "@angular/core";


@Injectable()
export class HomeService {

  private students = new Array<any>( //array details
    {
      name:"dwq",
      age:12,
      college:"2321"
    }
  )
}
2

1 Answer 1

1

After you create the service you have to inject that service to your component like this

  constructor(private homeServ:HomeService) {  }

then the service will be avilable in the componnet you can get the data

  ngOnInit(){
    this.students = this.homeServ.getStudents();
  }

demo 🚀

you can remove the injectable decorator from the service if the service has no dependency

read more about angular services 👉 her

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

Comments

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.