1. 子组件自定义属性接收父组件传递过来的参数<app-Title [title]="title"></app-Title>2. 在子组件中使用@Input进行注册import { Component, OnInit,Input} from '@angular/core';...export class TitleComponent implements OnInit { constructor() { } //Input 方法装饰器# @Input() item!:Object; ngOnInit() { }}3. 在子组件模板中直接使用
实例
# app.component.html<app-Title [list]="list"></app-Title>
# Title.component.tsimport { Component, OnInit,Input} from '@angular/core';@Component({ selector: 'app-Title', templateUrl: './Title.component.html', styleUrls: ['./Title.component.css']})export class TitleComponent implements OnInit { constructor() { } //Input 方法装饰器 @Input() list!:any; ngOnInit() { }}
# Title.component.html<div class="box"> <div class="item" *ngFor="let item of list"> <img class="img" src="{{item.coverImgUrl}}" alt=""> <p class="title">{{item.name}}</p> <span class="count"> {{item.playCount}} </span> </div></div>
# 数据请求 aoo,component.tsimport { Component } from '@angular/core';import {HttpClient} from "@angular/common/http"@Component({ //根主键 selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'my-app'; list:Array<any> = []; //list:any = []; constructor(public http:HttpClient){}; ngOnInit():void{ this.http.get("http://localhost:3000/top/playlist?cat=%E5%8D%8E%E8%AF%AD").subscribe((res:any) =>{ this.list = res.playlists; this.list.forEach(item =>{ item.playCount = this.handleCount(item.playCount) }) console.log(this.list); }) }; handleCount(value:any){ if(value>100000000){ return Math.floor(value/100000000)+"亿" }else if(value>10000){ return Math.floor(value/10000)+"万" }else{ return value } }}