禁用提交按钮,直到表单在有角度的反应形式+ onpush中有效

时间:2018-02-22 09:33:06

标签: angular angular5 angular-reactive-forms

如何在init上使用 onpush 停用提交按钮?

form.invalid无法使用onpush,在使用MarkForCheck手动更改检测之前,它不会在视图中更改为有效。我认为statusChanges会使用异步管道触发更改检测,因为它是可观察的,但在输入发生变化之前它不会发出值。

成分:

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: "ab-sign-in",
    templateUrl: "./sign-in.template.html",
})
export class SignInComponent implements OnInit {
    public form: FormGroup;
    public invalid$: Observable<boolean>;

    constructor(
        private formBuilder: FormBuilder,
    ) { }

    public ngOnInit(): void {
        this.form = this.formBuilder.group({
            email: ["", [Validators.required, emailValidator]],
            password: ["", Validators.required],
        });

        this.invalid$ = this.form.statusChanges
            .map((state) => state !== "VALID");
    }
}

HTML:

<form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>
    <input formControlName="email" type="email" />
    <input formControlName="password" type="password" />
    <button type="submit"
            [disabled]="invalid$ | async">
        LOG IN
    </button>
</form>

这里是plunker:

https://plnkr.co/edit/RMboNCrThQSZOskUuZSZ?p=preview

0 个答案:

没有答案