[英]How to pass data from one child component to another child component in angular2?
假設我有一個componentA和一個componentB
@Component({
selector: 'appA',
templateUrl: './appA.html',
styleUrls: ['./appA.css']
})
export class componentA{
constructor(private route: Router) { }
moveFront() {
this.route.navigateByUrl('componentB');
}
}
@Component({
selector: 'appB',
templateUrl: './appB.html',
styleUrls: ['./appB.css']
})
export class componentB{
constructor(private route: Router) { }
moveBack() {
this.route.navigateByUrl('componentA');
}
}
現在,當我調用moveFront()函數時,componentB被調用但我想將一些數據傳遞給組件,我該怎么做?
我的組件都是子組件,我想將數據傳輸到一個子組件和從另一個子組件傳輸數據。 我該怎么做。
要在Angular中傳遞數據,您可以使用@Input
將數據從父傳遞到子@Output
以將數據從子傳遞到父級
要在兄弟組件之間傳遞數據,您需要通過父組件傳遞,或者您需要使用服務https://angular.io/guide/component-interaction#parent-interacts-with-child-via-local-variable
另一個選項(如果您只發送字符串值)是使用Route params。 與查詢參數類似,它有一些看起來非常粗糙的URL的潛力,但它是一個選項。 首先,您將注入ActivatedRoute
:
constructor(private router: Router, private route:ActivatedRoute) { }
你會使用router.navigate
:
this.router.navigate(['componentB', {myVar:'myValue'}]);
然后在您的組件中,訂閱路徑參數:
ngOnInit() {
this.route.params.subscribe((data) => {
this.myVar = data.myVar || 'defaultValue';
});
}
同樣,這只適用於字符串。 Angular在使用此方法傳遞的任何Object上調用.toString()
。 如果您想發送更復雜的數據,則應使用服務/商店。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.