【问题标题】:How to pass ngForm to child component?如何将 ngForm 传递给子组件?
【发布时间】:2021-02-18 18:49:30
【问题描述】:

我有一个自定义输入组件,我想以多种形式重复使用它。但是我怎样才能将父母的表单上下文传递给它呢?我已经设法通过传递FormGroup 实例和字段名称来使用响应式表单来做到这一点。我正在尝试使用模板驱动的表单来实现相同的目标,但到目前为止我还没有成功。这是我的代码:

<!-- parent.component.html -->
<form #form="ngForm" (ngSubmit)="console.log(JSON.stringify(f.value))">
  <input name="someField" ngModel />
  <app-child name="myField"></app-child>
  <button type="submit">Submit</button>
</form>
<!-- child.component.html -->
<input ngModel [name]="name" />
// child.component.ts
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
})
class ChildComponent {
  @Input() name: string;
}

绑定不正确,因为提交表单时f.value.myField没有定义,只有f.value.someField。我怎样才能做到这一点?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以使用ngModelGroup 指令,然后在您的子组件中提供它,如下所示,这是一个有效的stackblitz

    <form #form="ngForm" (ngSubmit)="console.log(JSON.stringify(f.value))">
      <input name="someField" ngModel />
      <app-child ngModelGroup="myField"></app-child> // here
      <button type="submit">Submit</button>
    </form>
    
    // child.component.ts
    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrls: ['./child.component.css'],
      viewProviders: [{provide: ControlContainer, useExisting: NgModelGroup}] // here
    })
    class ChildComponent {
      @Input() name: string;
    }
    

    【讨论】:

    • 嗯...当我这样做时,f.value.myField 的计算结果为 {},而不是未定义。这是一个开始。编辑还抱怨"No provider for ControlContainer"(在parent.component.html),但代码运行良好。
    • 给我几分钟,我会发布一个有效的堆栈闪电战
    • 别着急,我的工作日已经结束了?。提前致谢!
    • 我在答案中添加了链接
    • 它有效。谢谢!然而,这并不是我想要的。这个更适合我的需要:stackoverflow.com/questions/50618050/…
    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-06
    • 2020-05-07
    • 2020-03-30
    • 2017-12-02
    相关资源
    最近更新 更多