子元素的angular2动态高度 @组件({ 选择器:“sc”, templateUrl:' ', 指令:[反应形式指令] }) 导出类SCComponent实现OnInit,AfterViewInit{ ....... }

子元素的angular2动态高度 @组件({ 选择器:“sc”, templateUrl:' ', 指令:[反应形式指令] }) 导出类SCComponent实现OnInit,AfterViewInit{ ....... },angular,angular2-template,angular2-forms,Angular,Angular2 Template,Angular2 Forms,我需要设置表单的高度,当sc组件初始化时,该高度可能与div高度不同。我尝试了上面的cntfrm方法,将变量高度引用到div高度,但被忽略了。但是我可以在UI上使用插值来显示{{cntfrm.clientHeight}}的值。只是一个想法,也许您可以尝试以下方法: @Component({ selector: 'sc', templateUrl: '<div> <form id="frmId" #cntfrm [formGroup]="scForm">

我需要设置表单的高度,当
sc
组件初始化时,该高度可能与div高度不同。我尝试了上面的
cntfrm
方法,将变量高度引用到div高度,但被忽略了。但是我可以在UI上使用插值来显示
{{cntfrm.clientHeight}}
的值。

只是一个想法,也许您可以尝试以下方法:

   @Component({
    selector: 'sc',
    templateUrl: '<div>
<form id="frmId" #cntfrm [formGroup]="scForm">

</form>
<div id="boxId" [style.height.px]= "cntfrm.clientHeight">
</div>
</div>
',
    directives: [REACTIVE_FORM_DIRECTIVES]
})
export class SCComponent implements OnInit, AfterViewInit {
.......
}
编辑
创建了一个plunker:

只是一个想法,也许你可以尝试以下内容:

   @Component({
    selector: 'sc',
    templateUrl: '<div>
<form id="frmId" #cntfrm [formGroup]="scForm">

</form>
<div id="boxId" [style.height.px]= "cntfrm.clientHeight">
</div>
</div>
',
    directives: [REACTIVE_FORM_DIRECTIVES]
})
export class SCComponent implements OnInit, AfterViewInit {
.......
}
编辑 创建了一个plunker:

实际上,问题是我的表单是使用ngif绑定的模板。因此,表单在ngAfterView之前不会呈现。如果我在ngOnInit中指定表单高度,我会得到未定义的错误。如果我在ngAfterView中正常分配它,我会得到角度单向误差,因为在合成视图后状态会发生变化。所以,我必须在下一个周期中使用setinterval来完成它。另一个选项是启用生产模式。我猜在这种模式下,角度变化检测为每个事件循环解析两次


实际上,问题是我的表单是使用ngif绑定的模板。因此,表单在ngAfterView之前不会呈现。如果我在ngOnInit中指定表单高度,我会得到未定义的错误。如果我在ngAfterView中正常分配它,我会得到角度单向误差,因为在合成视图后状态会发生变化。所以,我必须在下一个周期中使用setinterval来完成它。另一个选项是启用生产模式。我猜在这种模式下,角度变化检测为每个事件循环解析两次

我在ngAfterViewInit()中尝试了this.formHeight=this.cntfrm.nativeElement.clientHeight。我使用了@ViewChild('cntfrm')cntfrm:ElementRef;获取cntfrm引用。但我得到了ExpressionChangedTerithasBeenCheckedException.BaseException。这是由于angular2单向更改检测策略造成的。我可以在prod模式下避免它。但是应该有更好的方法来处理两个子元素高度的简单同步而不是
document.getElementById(…)
ngOnInit()
也是此代码的错误方法。它应该是
ngAfterViewInit()
,以确保实际构建DOM。我在ngAfterViewInit()中尝试了this.formHeight=this.cntfrm.nativeElement.clientHeight。我使用了@ViewChild('cntfrm')cntfrm:ElementRef;获取cntfrm引用。但我得到了ExpressionChangedTerithasBeenCheckedException.BaseException。这是由于angular2单向更改检测策略造成的。我可以在prod模式下避免它。但是应该有更好的方法来处理两个子元素高度的简单同步而不是
document.getElementById(…)
ngOnInit()
也是此代码的错误方法。它应该是
ngAfterViewInit()
,以确保实际构建了DOM。控制台中是否有错误?控制台中是否有错误?
ngAfterViewChecked(){

    setTimeout(()=>{ this.height = this.el.getElementsByClassName("form")[0].clientHeight;}, 0); 
 }