【问题标题】:ngForm reference variable return undefined in ng-templatengForm 引用变量在 ng-template 中返回未定义
【发布时间】:2018-06-15 10:45:03
【问题描述】:

我正在尝试在自定义组件中注入表单,并且正在动态加载该组件。对于这种情况,在引用 ngForm 模板变量时,我得到了未定义:

<app-custom-component [template]="myTemplate">
    <ng-template #myTemplate>
        <form #myForm="ngForm">
            .....
        </form>
    </ng-template>
</app-custom-component>

现在在我的component.ts

@ViewChild('myForm') myForm;
ngAfterViewInit() {
    this.buyAmountForm.valueChanges.subscribe(values => this.validate()); //--> undefined, no valueChanges
}

如果我删除 ng-template,一切正常。有什么办法可以解决这个问题?

【问题讨论】:

  • 为什么需要模板???
  • 使用@ViewChildren('myForm')QueryList.changes事件,如this answer所示。
  • 反对投票的任何理由......为什么我需要模板?这是因为我有一个可重用的组件并且那里有一个模板输出.....我认为可能是实现错误,或者可能有黑客或解决方法

标签: javascript angularjs angular angular4-forms


【解决方案1】:

使用{descendants: true}访问后代

@ViewChild('myForm', {descendants: true}) myForm;

【讨论】:

  • 试过了,得到这个错误:Argument of type '{ descendants: boolean; }' 不能分配给 '{ read?: any; 类型的参数。 }'
猜你喜欢
  • 2019-07-13
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
  • 2020-11-28
  • 2012-01-16
相关资源
最近更新 更多