简体   繁体   中英

angular reactive forms disable field

I have a simple reactive form and I'm using Angular material framework.

this.firstFormGroup = this.fb.group({
            builder_first_name: ['', Validators.required],
            builder_last_name: ['', Validators.required]
        });

And edit function that is saving this data.

handleEdit(event): void {
    event.preventDefault();
    this.firstFormGroup.markAllAsTouched();
    if (!this.firstFormGroup.valid) {
        return;
    }
    this.mySerivce.update(this.firstFormGroup.value, this.project.id)
}

I want to make a last_name field readonly for some kind of users. But after I added simple logic:

builder_last_name: [{value: '', disabled: currentUser$.isAdmin ? false : true}, Validators.required]

I noticed that this.firstFormGroup.valid returns false right now.

I read this topic: https://github.com/angular/angular/issues/11432

But I still didn't find good solution how to handle all this. I tried readonly attribute, but how to deal with <select> and styles that applied to mat- fields that been disabled?

Thanks to @Eliseo.

When I changed condition to this.firstFormGroup.invalid everything is works as expected. I also changed this.firstFormGroup.value to this.firstFormGroup.getRawValue() to make sure that all field values is captured correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM