簡體   English   中英

Angular - 如何通過路由將數據從子組件發送到父組件?

[英]Angular - How to send Data from Child Component to Parent with Routing?

我想設置一個 SampleData 並將其發送到 Angular 中的父組件。 當子組件純粹在父組件內部時,它工作正常。

但是,我想通過路由在父組件中設置不同的子組件。

所以我把在 parent.component.html 中,子組件是這樣調用的,並且不再工作......

{ path: "sample1", component: Sample1Component }

誰能看到我的代碼並給我一個解決方案......?

中心組件將是父組件,而 Sample1 組件將是子組件。

您可以從這里下載代碼以查看更多詳細信息

app.router.module.ts

const AppRoutes: Routes = [
  { path: "", redirectTo: "/", pathMatch: "full" }, 
  { path: "sample1", component: Sample1Component },
  { path: "**", redirectTo: "/", pathMatch: "full" } 
];

center.component.html

<div (sampleEvent)="SampleData = $event">
  Center Area Title from Sample 1 : {{ SampleData }}
</div>

<!--if sample 1 Component is called by this Router, 'Center Area Title value does not change -->
<router-outlet></router-outlet>

<!-- if sample 1 Component is called by below, 'Center Area Title value changes-->
<!-- <app-sample1 (sampleEvent)="SampleData = $event"></app-sample1> -->

sample1.component.html

<input type="text" placeholder="Center Area Title" #sampleTitle (keyup)="onChange(sampleTitle.value)"  />

sample1.component.ts

export class Sample1Component implements OnInit {
  @Output("sampleEvent") sampleEvent = new EventEmitter();

  onChange(value) {
    console.log(value);
    this.sampleEvent.emit(value);
  }

  constructor() {}
  ngOnInit() {}
}

請有人幫我在這里....

路由組件與包含RouterOutlet ( <router-outlet> ) 的組件沒有內在的關系。 可能找到一種方法通過RouterOutlet從路由組件發出數據,但這不是解決此問題的規范方法。 更傳統的解決方案是使用外部單例(服務),其中包含用於在沒有直接繼承關系的組件之間傳輸數據的 observable。

  1. 為事件創建一個帶有Subject字段的@Injectable()服務類
  2. 將此服務添加到模塊提供程序
  3. 噴射該服務入兩個路線成分( Sample1Component )和容器組件( CenterComponent
  4. 偵聽容器組件 ( CenterComponent ) 中 observable 字段的更改
  5. 對路由組件中的可觀察主題發出更改 ( Sample1Component )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM