Angular Material 2在提交

时间:2017-08-03 15:24:58

标签: angular validation input angular2-forms angular-material2

我正在尝试在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],
    });
  }
}

我有一个带有一个嵌套formController的简单formGroup。这是我的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 个答案:

答案 0 :(得分: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