首页 文章

Angular Material 2在提交时嵌套表单验证

提问于
浏览
2

我正在尝试在Angular 2中使用带有formGroup的Angular材质,并且我对不同组件中的嵌套formControls的输入验证存在问题 .

我的问题是:提交表单时,只有第一个formGroup中的输入才会收到表单已提交的通知 .

我创建了以下示例:

@Component({
  selector: 'material-app',
  templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
  public myForm: FormGroup;

  constructor(private _fb: FormBuilder) {}

    ngOnInit() {
    this.myForm = this._fb.group({
      nested: this._fb.group({
           id: ['', Validators.required]
      }),
      id: ['', Validators.required],
    });
  }
}

我有一个简单的formGroup与一个嵌套的formController . 这是我的HTML:

<form [formGroup]="myForm">
  <md-input-container>
    <input mdInput required formControlName="id">
  </md-input-container>
  <other-component [myFormGroup]="myForm" myFormGroupName="nested"></other-component>
  <button md-raised-button type="submit">Rechercher</button>
</form>

另一个组件只显示另一个输入 .

我做了一个插图来说明:http://plnkr.co/edit/WR0cmVOhIfCdkqAVc8xX

您可以注意到,如果我输入一个字段并立即退出,则两个输入上都会出现红色错误行 . 但是,如果我没有触及两个输入,我点击提交,只有非嵌套输入加下划线 . 这是因为嵌套的不会获得表单提交的信息,即使我将formGroup对象作为参数传递 .

我知道如何解决这个问题?如何让第一个输入知道提交的表单?

非常感谢 !

1 回答

  • 1

    Angular不会将 mat-input-invalid 类添加到嵌套控件中 . 我们想为什么?

    以下是 MdInputContainer 的类绑定如何:

    '[class.mat-input-invalid]': '_mdInputChild._isErrorState',
    

    这是相应的样式,使您的边框变红 .

    .mat-input-invalid .mat-input-ripple {
        background-color: #f44336; // red
    }
    

    如果您将调查如何计算 _isErrorState 属性,您可以注意到它检查 FormGroupDirective.submitted 属性 .

    function defaultErrorStateMatcher(control, form) {
        var /** @type {?} */ isSubmitted = form && form.submitted; <----
        return !!(control.invalid && (control.touched || isSubmitted));
    }
    

    由于您要创建两个 FormGroupDirective 指令,因此只会提交顶级指令 .

    你可以使用反应 FormControlDirective 来解决它

    other.component.ts

    @Component({
      selector: 'other-component',
      template: `
          <md-input-container >
            <input mdInput required [formControl]="control">
          </md-input-container>
      `
    })
    export class OtherComponent  {
      @Input() subname: string;
      @Input() formobj: any;
    
      control: FormControl;
    
      ngOnInit() {
        this.control = this.formobj.get([this.subname, 'id'])
      }
    }
    

    Plunker Example

相关问题