我正在嘗試將資料從父組件傳遞到子組件。我有類似的東西:
父組件:
@Component({
selector: 'foo-parent',
templateUrl: './foo-parent.component.html',
styleUrls: ['./foo-parent.component.scss'],
})
export class FooParent {
@Input() data: any;
constructor() { }
}
父級從執行所有邏輯的另一個庫中接收資料。
孫子組件:
@Component({
selector: 'foo-grand-child',
templateUrl: './foo-grand-child.component.html',
styleUrls: ['./foo-grand-child.component.sass'],
})
export class FooGrandChild {
data: any;
constructor(private fooParent: FooParent) {
this.data = this.fooParent.fooGrandChildData;
}
這種方法可以正常作業,但我是新手,我不知道這是否是正確的方法。除了橋接父>子>孫子組件之外,還有其他方法嗎?
uj5u.com熱心網友回復:
我認為這不是Angular在組件之間傳遞資料的方式。正如您已經知道組件之間的關系(這很好),您可以選擇正確的組件之間的通信方法。
我建議閱讀 https://fireship.io/lessons/sharing-data-between-angular-components-four-methods/
至于你的用例。父母到孫子。
我建議使用一個Service,那就是設定field/property你Parent Component和那么你的Grandchild Component獲取field/property,而不是直接Injecting對Parent Component您的Grandchild Component
父組件
@Component({
selector: 'foo-parent',
templateUrl: './foo-parent.component.html',
styleUrls: ['./foo-parent.component.scss'],
})
export class FooParent implements OnInit {
constructor(private sharedtestService: SharedTestService) { }
ngOnInit(): void {
this.sharedtestService.setTestData('string');
}
}
孫子組件
@Component({
selector: 'foo-grand-child',
templateUrl: './foo-grand-child.component.html',
styleUrls: ['./foo-grand-child.component.sass'],
})
export class FooGrandChild implements OnInit {
data: string;
constructor(private sharedtestService: SharedTestService) {}
ngOnInit(): void {
this.data = this.sharedtestService.getTestData();
}
}
共享服務
@Injectable({
providedIn: 'root'
})
export class SharedTestService {
testData: string;
constructor() {}
setTestData(temp: string): void {
return this.testData = temp;
}
getTestData(): string {
return this.testData;
}
}
我也建議尋找到Observables如何訂閱它們,如果你希望你的GrandChildren Component自動聽由你做的改變Parent Component。
uj5u.com熱心網友回復:
有幾件事,首先,如果您想將某些內容從父級傳遞給子級,然后從子級(您接收資料的地方)中的子級(父組件的孫子級),我們使用 @Input() 裝飾器不在父母中。@Input() 資料在 @output() 資料在外面。這就是為什么應該在子組件上使用 @Input() 的原因。在子組件中擁有 @Input 后??,您可以通過 HTML 將值傳遞給該變數。我給你看一個例子:
兒童(ts):
@Component({
selector: 'child-sample-component',
templateUrl: './child-sample-component.component.html',
})
export class ChildSampleComponenet {
@Input() childObject;
}
家長(html):
<child-sample-component [childObject]="parentObject">
</child-sample-component>
請注意,在子項中我們如何使用帶有 childObject 變數的 @Input 以及在父 html 中我們如何使用包含任何內容的 parentObject 父變數將值賦給 childObject。
還有其他方法,例如使用服務等。但是您應該邊走邊學。這里有幾個有趣的鏈接。
https://angular.io/guide/inputs-outputs
https://angular.io/guide/architecture-services
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/421065.html
標籤:
下一篇:角度對話框不顯示訊息
