Angular2:我怎样才能有一个父组件告诉孩子什么大小?
我的角度2.工作,我有一个组件 - 弦图 - 我想在这取决于各种尺寸哪些父组件它包含在显示Angular2:我怎样才能有一个父组件告诉孩子什么大小?
我有一个细节显示我想要的。和弦图组件的高度:500px和宽度:700px。
我有一个仪表板显示器,我希望和弦图组件是高度:200px和宽度:300px。
我试图通过使用@Input将尺寸传递给和弦图来做到这一点。
弦graph.component.ts:
export class ChordGraphComponent {
@Input() dimensions: {height: number, width: number};
}
弦graph.component.html:
<div #container [ngStyle]="{ 'height.px': dimensions.height, 'width.px': dimensions.width }"></div>
细节view.component.ts:
export class DetailViewComponent {
dimensions: { height: number, width: number} = {height: 500, width: 700};
}
细节-view.component.html:
<chord-graph [dimensions]=dimensions></chord-graph>
仪表板view.component.ts:
export class DashboardViewComponent {
dimensions: { height: number, width: number} = {height: 200, width: 300};
}
仪表板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中将高度/宽度设置为数字,那么页面将使用该尺寸的元素加载。
你可以跳过只有CSS属性和样式的样式。每个家长可以通过设置共同的孩子风格:
:host ::ng-deep chord-graph{
width: 200px;
height: 100px;
}
是的,<div #container [ngStyle]="{ 'height.px': dimensions?.height, 'width.px': dimensions?.width }"></div>
表达式运算符(https://angular.io/guide/template-syntax#expression-operators)应该有所帮助。
此外,@Input属性具有默认值也很好。
试着改变你的弦graph.component.html到''
组件可能正在尝试设置高度/宽度尺寸就是为什么使用[维度定义 – LLai前] =维度,意思是说没有任何引号,财产应该用在报价中,是不是真的? –
我已经创建了一个满足您问题的插入式示例,并且所有内容都按预期工作。请看看这个plunk:https://embed.plnkr.co/HNdP93kZYvl7UGJkwX4M/也许我错过了一些东西。 – hakobpogh