【问题标题】:Angular 11 how to initialize the Child's formgroup values?Angular 11 如何初始化 Child 的 formgroup 值?
【发布时间】:2021-09-07 20:52:30
【问题描述】:

在父 HTML 中已定义为这样 -

 <div class="modal-body">
          <app-addchild [childform]="element"></app-addchild>
 </div>

这里的元素是JSON格式的行数据,带有字段值。

childform 是定义为 @Input() 的表单组,子组件是这样的 -

 @Input() public childform = new FormGroup({
      code: new FormControl('', [Validators.required, Validators.pattern('[0-9]+')]),
      countryCode: new FormControl('', Validators.required),
      ...
    });

【问题讨论】:

    标签: angular angular11


    【解决方案1】:

    您可以像这样为@Input 赋值。你可以这样做

    @Input() set childform(value) {
          // value is data passed to the input
         // you can do something like this
         this.gnpform.get('code').setValue(value.code);
    }
    
    
    public gnpform = new FormGroup({
          code: new FormControl('', [Validators.required, Validators.pattern('[0-9]+')]),
          countryCode: new FormControl('', Validators.required),
          ...
        });
    

    【讨论】:

    • 我会将set childform(value) 更改为set code(value) 以更好地反映它在做什么。
    • 是的,这取决于你。您可以使用任何命名约定。它应该可以工作。
    • 感谢 Apoorva Chikara :+1: 帮助。
    • 如果可行,您可以接受答案以供将来参考。你也会因此获得奖励。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多