一、页面渲染

1-1、取数据

  1. //app.module.ts
  2. import {HttpClientModule} from '@angular/common/http'
  3. imports:[
  4. ...,
  5. HttpClientModule
  6. ]
  7. //app.component.ts
  8. import {Component} from '@angular/core'
  9. import {HttpClient} from '@angular/common/http'
  10. ...
  11. export class AppComponent {
  12. public playlists:any;
  13. constructor(public http:HttpClient) { }
  14. title = 'my-ng-music';
  15. ngOnInit() {
  16. var url:string = "http://192.168.14.15:5000/top/playlist"
  17. this.http.get(url).subscribe(res=>{
  18. // console.log(res['playlists'])
  19. this.playlists = res['playlists']
  20. })
  21. }
  22. }

1-2、渲染页面

  1. //app.component.html
  2. <app-item [playlists]="playlists"></app-item>
  3. //在子组件中
  4. //.ts
  5. import {Component,OnInit,Input} from '@angular/core'
  6. ...
  7. export class ItemComponent implements OnInit {
  8. @Input() playlists:string;
  9. constructor() { }
  10. ngOnInit() {
  11. }
  12. }
  13. //.html
  14. <div class="wrap">
  15. <div *ngFor="let item of playlists">
  16. <img class="cover" src={{item.coverImgUrl}} alt="">
  17. <p class="name">{{item.name}}</p>
  18. </div>
  19. </div>

二、点击删除

  1. //子组件
  2. //.html
  3. <div class="wrap">
  4. <div *ngFor="let item of playlists,let index = index" (click)="handleClick(index)">
  5. ...
  6. </div>
  7. </div>
  8. //.ts
  9. import {Component,OnInit,Input} from '@angular/core'
  10. ...
  11. export class ItemComponent implements OnInit {
  12. ...
  13. @Input() getId:any;
  14. constructor() { }
  15. ngOnInit() {
  16. }
  17. handleClick(index){
  18. this.getId(index)
  19. }
  20. }
  1. //父组件
  2. //.html
  3. <app-item ... [getId]="getId"></app-item>
  4. //.ts
  5. export class AppComponent {
  6. ...
  7. /* 通过index删除 */
  8. getId(index:number){
  9. this.playlists.splice(index,1);
  10. }
  11. }