簡體   English   中英

Angular2:如何讓父組件告訴孩子要多大的尺寸?

[英]Angular2: How can I have a parent component tell a child what size to be?

我正在Angular 2中工作。我有一個組件-和弦圖-我想根據其所包含的父組件以各種大小顯示它。

我有一個詳細的顯示,我希望將和弦圖分量設為高度:500px和寬度:700px。

我有一個儀表板顯示器,我希望和弦圖組件的高度為:200px,寬度為:300px。

我嘗試通過使用@Input將尺寸傳遞給和弦圖來實現此目的。

chord-graph.component.ts:

export class ChordGraphComponent {
    @Input() dimensions: {height: number, width: number};
}

chord-graph.component.html:

<div #container [ngStyle]="{ 'height.px': dimensions.height, 'width.px': dimensions.width }"></div>

detail-view.component.ts:

export class DetailViewComponent {
    dimensions: { height: number, width: number} = {height: 500, width: 700};
}

detail-view.component.html:

<chord-graph [dimensions]=dimensions></chord-graph>

dashboard-view.component.ts:

export class DashboardViewComponent {
    dimensions: { height: number, width: number} = {height: 200, width: 300};
}

dashboard-view.component.html:

<chord-graph [dimensions]=dimensions></chord-graph>

當前,這將引發TypeError: Cannot read property 'height' of undefined at CompiledTemplate.proxyViewClass.View_ChordGraphComponent0.detectChangesInteral 如果我在chord-graph.component.html中將高度/寬度設置為一個數字,則頁面將以該大小加載元素。

是的, <div #container [ngStyle]="{ 'height.px': dimensions?.height, 'width.px': dimensions?.width }"></div>表達式運算符( https://angular.io / guide / template-syntax#expression-operators )應該會有所幫助。

另外,最好為@Input屬性設置默認值。

您可能可以僅使用CSS跳過具有屬性和樣式的樣式。 每個父母都可以通過以下方式設置普通兒童樣式:

 :host ::ng-deep chord-graph{
   width: 200px;
   height: 100px;
 }

暫無
暫無

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

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