一、页面渲染
1-1、取数据
//app.module.tsimport {HttpClientModule} from '@angular/common/http'imports:[ ..., HttpClientModule]//app.component.tsimport {Component} from '@angular/core'import {HttpClient} from '@angular/common/http'...export class AppComponent { public playlists:any; constructor(public http:HttpClient) { } title = 'my-ng-music'; ngOnInit() { var url:string = "http://192.168.14.15:5000/top/playlist" this.http.get(url).subscribe(res=>{ // console.log(res['playlists']) this.playlists = res['playlists'] }) }}
1-2、渲染页面
//app.component.html<app-item [playlists]="playlists"></app-item>//在子组件中//.tsimport {Component,OnInit,Input} from '@angular/core'...export class ItemComponent implements OnInit { @Input() playlists:string; constructor() { } ngOnInit() { }}//.html<div class="wrap"> <div *ngFor="let item of playlists"> <img class="cover" src={{item.coverImgUrl}} alt=""> <p class="name">{{item.name}}</p> </div></div>
二、点击删除
//子组件//.html<div class="wrap"> <div *ngFor="let item of playlists,let index = index" (click)="handleClick(index)"> ... </div></div>//.tsimport {Component,OnInit,Input} from '@angular/core'...export class ItemComponent implements OnInit { ... @Input() getId:any; constructor() { } ngOnInit() { } handleClick(index){ this.getId(index) }}
//父组件//.html<app-item ... [getId]="getId"></app-item>//.tsexport class AppComponent { ... /* 通过index删除 */ getId(index:number){ this.playlists.splice(index,1); }}