表单上的onChange事件仅在模糊后发出输出事件



在应用程序表单组件中有一个表单。在"消费者组件"中(如果我错了,请纠正我,否则不确定该怎么称呼它(,如果该表单有效,我希望启用或禁用按钮。

因此,从消费者组件开始:

/app-ting.component.ts(消费者(

// ...imports
@Component({
selector: 'app-thing',
template: `
<app-form (isValidForm)="checkFormValidity($event)">
<ng-container action>
<button [disabled]="!buttonEnabled">Submit</button>
</ng-container>
</app-form>
`,
})
export class AppThing {
buttonEnabled = false;
checkFormValidity(isValid: boolean) {
this.buttonEnabled = isValid;
}
}

现在,为了监听事件,我正在使用形式为的onchange事件

/app-form.comcomponents.ts(动态组件(

// ...imports
@Component({
selector: 'app-form',
template: `
<form [formGroup]="form" (change)="formChange()">
<label>
Name:
<input type="text" formControlName="name" />
</label>
<ng-content select="[action]"></ng-content>
</form>
`
});
export class FormComponent {
@Output()
isValidForm = new EventEmitter<boolean>();
form = this.formBuilder.group({
name: ['', Validators.required],
});
constructor(private formBuilder: FormBuilder) {}
formChange() {
this.isValidForm.emit(this.form.valid);
}
}

但现在,只有当用户在输入更改后单击页面上的某个位置时,它才会启用或禁用按钮。

当输入值发生变化时,我如何更改它以启用/禁用按钮?

这里是一个工作示例。

我们可以使用FormGroupstatusChanges可观察属性来通知我们表单的状态何时更改。

// form.component.ts
@Component({
selector: "app-form",
templateUrl: "./form.component.html",
styleUrls: ["./form.component.css"]
})
export class FormComponent implements OnInit {
public nameForm: FormGroup;
@Output()
public readonly formValid$: Observable<boolean>;
constructor(private fb: FormBuilder) {
this.buildForm();
this.formValid$ = this.nameForm.statusChanges.pipe(
debounceTime(300),
map(() => this.nameForm.valid),
distinctUntilChanged()
);
}
ngOnInit() {}
private buildForm() {
this.nameForm = this.fb.group({
name: ["", Validators.required]
});
}
}

我们将其分配给formValid$可观测。

@Output装饰器用于将状态更改传递给我们的父组件。

我们使用debounceTimedistinctUntilChanged来限制发出的事件数量。

// app.component.ts
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
public onChangeFormValidity(formValid: boolean) {
console.log(formValid);
}
}

我们将onChangeFormValidity方法绑定到formValid$输出属性。

// app.component.html
<app-form (formValid$)="onChangeFormValidity($event)"></app-form>

最新更新