如何将数据从父组件传递到子组件并导航到 Angular 中的子页面?

How to pass data from parent component to child component and navigate to child page in Angular?

我已经创建了父组件和子组件,我正在尝试将数据从父组件传递到子组件并导航到子页面。但是当我导航到子页面时数据没有被传递。当我在同一页面中显示子组件时,数据正在传递。下面我添加了代码。如果我删除 this.router.navigate(['/single-track']); 行,它会起作用。但我希望它应该导航到其他页面并显示在那里。

Parent.html

    <div class="row">
        <div class="col-md-10">
            <div class="card" *ngFor="let track of trackList">
                <div class="name">{{track.productName}}</div>
                <div class="tracklink">
                    <audio controls>
                        <source src="{{track.imageUrl}}" type="audio/mpeg">
                    </audio>
                </div>
                <div><span (click)="TrackPage(track)"><i class="fa fa-arrow-right"></i></span></div>
            </div>
        </div>
    </div>
</div>
<app-main-track-page [currentTrack] = "currentTrack" *ngIf="value"></app-main-track-page>

Parent.ts

import { GetTrackService } from '../get-track.service';
import { track } from '../track';
import { Router } from '@angular/router'

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
  trackList: track[];
  currentTrack:track;
  value:boolean = false;

  constructor(private getdata: GetTrackService, private router:Router) { }

  ngOnInit() {
    this.getdata.getTrack().subscribe(
      data => this.trackList = data
    );
  }

  TrackPage(track:track):void{
    this.currentTrack = track;
    console.log("Home track: ", this.currentTrack)
    this.value = true;
    this.router.navigate(['/child']);
  }
}

Child.html


<div class="container" style="margin-top: 50px;">
    <div class="row">
        <div class="col-md-10">
            <div class="card">
                <div class="name">{{currentTrack.productName}}</div>
                <div class="tracklink">
                    <audio controls>
                        <source src="{{currentTrack.imageUrl}}" type="audio/mpeg">
                    </audio>
                </div>
            </div>
        </div>
    </div>
</div>

Child.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-main-track-page',
  templateUrl: './main-track-page.component.html',
  styleUrls: ['./main-track-page.component.css']
})
export class MainTrackPageComponent implements OnInit {

  @Input() currentTrack:track;
  trackList: track[];
  constructor() { }

  ngOnInit() {
    console.log("currentTrack: ",  this.currentTrack)

  }

}

您可以创建通用数据共享服务并将其包含在您的模块的提供程序中。 在父组件中设置数据后,在子组件中更改路由后即可获取数据。

当您导航时组件被销毁。所以为了保持传递的数据,存储起来。创建服务并将其存储在那里。 导航后从服务中检索它