1. 1. 子组件自定义属性接收父组件传递过来的参数
  2. <app-Title [title]="title"></app-Title>
  3. 2. 在子组件中使用@Input进行注册
  4. import { Component, OnInit,Input} from '@angular/core';
  5. ...
  6. export class TitleComponent implements OnInit {
  7. constructor() { }
  8. //Input 方法装饰器
  9. # @Input() item!:Object;
  10. ngOnInit() {
  11. }
  12. }
  13. 3. 在子组件模板中直接使用

实例

  1. # app.component.html
  2. <app-Title [list]="list"></app-Title>
  1. # Title.component.ts
  2. import { Component, OnInit,Input} from '@angular/core';
  3. @Component({
  4. selector: 'app-Title',
  5. templateUrl: './Title.component.html',
  6. styleUrls: ['./Title.component.css']
  7. })
  8. export class TitleComponent implements OnInit {
  9. constructor() { }
  10. //Input 方法装饰器
  11. @Input() list!:any;
  12. ngOnInit() {
  13. }
  14. }
  1. # Title.component.html
  2. <div class="box">
  3. <div class="item" *ngFor="let item of list">
  4. <img class="img" src="{{item.coverImgUrl}}" alt="">
  5. <p class="title">{{item.name}}</p>
  6. <span class="count">
  7. {{item.playCount}}
  8. </span>
  9. </div>
  10. </div>
  1. # 数据请求 aoo,component.ts
  2. import { Component } from '@angular/core';
  3. import {HttpClient} from "@angular/common/http"
  4. @Component({
  5. //根主键
  6. selector: 'app-root',
  7. templateUrl: './app.component.html',
  8. styleUrls: ['./app.component.css']
  9. })
  10. export class AppComponent {
  11. title = 'my-app';
  12. list:Array<any> = [];
  13. //list:any = [];
  14. constructor(public http:HttpClient){};
  15. ngOnInit():void{
  16. this.http.get("http://localhost:3000/top/playlist?cat=%E5%8D%8E%E8%AF%AD").subscribe((res:any) =>{
  17. this.list = res.playlists;
  18. this.list.forEach(item =>{
  19. item.playCount = this.handleCount(item.playCount)
  20. })
  21. console.log(this.list);
  22. })
  23. };
  24. handleCount(value:any){
  25. if(value>100000000){
  26. return Math.floor(value/100000000)+"亿"
  27. }else if(value>10000){
  28. return Math.floor(value/10000)+"万"
  29. }else{
  30. return value
  31. }
  32. }
  33. }