Disable input on angular form

﹥>﹥吖頭↗ 提交于 2020-03-01 04:40:33

问题


Hi i'm using angular 7 and i want to disable the input that retrieves the user information but when I use, [disabled] = true it does not work I want to disable the lastname field , I try this but when I do it and when I send my form, it does not send the input disabled on the json

This is my form in code html :

<div id="forms" class="page-layout simple fullwidth" fxLayout="column">

    <!-- HEADER -->
    <div class="header accent p-24 h-160" fxLayout="row" fxLayoutAlign="start center">
        <div fxLayout="column" fxLayoutAlign="center start">
            <div fxLayout="row" fxLayoutAlign="start center">
                <mat-icon class="secondary-text s-18">home</mat-icon>
                <mat-icon class="secondary-text s-16">chevron_right</mat-icon>
                <span class="secondary-text">Contact</span>
            </div>
            <div class="h1 mt-16">Contact</div>
        </div>
    </div>
    <!-- / HEADER -->
    <div class="content p-24">
        <p class="pt-16 pb-32">
            {{'contact.Veuillez remplir le formulaire ci-dessous pour effectuer votre demande.Nous allons traiter votre requête dans les plus brefs délais.' | translate}}
        </p>
        <div class="mb-24" fxLayout="column" fxLayoutAlign="center center" fxLayout.gt-md="row">
            <form class="mat-card mat-elevation-z4 p-24 mr-24" fxLayout="column" fxLayoutAlign="start" fxFlex="1 0 auto"
                name="form" [formGroup]="form">

                <div class="" style="text-align: center">
                    <img class="logo-ca" src="assets/images/logos/snap.png">
                </div>
                <div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">

                    <mat-form-field appearance="outline" fxFlex="50" class="pr-4">
                        <mat-label>{{'contact.First name' | translate}}</mat-label>
                        <input matInput formControlName="firstname">
                        <mat-icon matSuffix class="secondary-text">account_circle</mat-icon>
                    </mat-form-field>

                    <mat-form-field appearance="outline" fxFlex="50" class="pl-4">
                        <mat-label>{{'contact.Last name' | translate}}</mat-label>
                        <input matInput formControlName="lastname">
                        <mat-icon matSuffix class="secondary-text">account_circle</mat-icon>
                    </mat-form-field>

                </div>

                <div fxLayout="row wrap" fxLayoutAlign="start center" fxFlex="1 0 auto">
                    <mat-form-field appearance="outline" fxFlex="100" class="pl-4">
                        <mat-label>{{'contact.Mail' | translate}}</mat-label>
                        <input matInput formControlName="email">
                        <mat-icon matSuffix class="secondary-text">mail</mat-icon>
                    </mat-form-field>
                </div>
                <div fxLayout="row wrap" fxLayoutAlign="start center" fxFlex="1 0 auto">
                    <mat-form-field appearance="outline" fxFlex="100" class="pl-4">
                        <mat-label>Groupe AD</mat-label>
                        <input matInput formControlName="group" required [pattern]="groupPattern">
                        <mat-icon matSuffix class="secondary-text">group</mat-icon>
                        <mat-error *ngIf="group.errors?.required">{{'contact.Groupe AD is required!' | translate}}
                        </mat-error>
                        <mat-error *ngIf="group.errors?.pattern">{{'contact.Groupe AD is not Valid!' | translate}}
                        </mat-error>
                    </mat-form-field>
                </div>
                <div formArrayName="requested_domains"
                    *ngFor="let domain of form.controls.requested_domains.controls; let i = index" fxLayout="row wrap"
                    fxLayoutAlign="start center" fxFlex="1 0 auto">
                    <div [formGroupName]="i" fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
                        <mat-form-field appearance="outline" fxFlex="40" class="pl-4">
                            <mat-label>Domaines</mat-label>
                            <input matInput formControlName="domain_name" required [pattern]="domainPattern">
                            <mat-error *ngIf="requested_domains.errors?.required">
                                {{'contact.Groupe AD is required!' | translate}}</mat-error>
                            <mat-error *ngIf="requested_domains.errors?.pattern">
                                {{'contact.Groupe AD is not Valid!' | translate}}</mat-error>
                        </mat-form-field>
                        <!--                         <mat-form-field appearance="outline" fxFlex="30" class="pl-4">
                            <mat-label>Right</mat-label>
                            <mat-select placeholder="Right" formControlName="right" required>
                                <mat-option value="R">R</mat-option>
                                <mat-option value="RW">RW</mat-option>
                            </mat-select>
                        </mat-form-field> -->
                        <mat-radio-group  formControlName="right" aria-label="Select an option" appearance="outline" fxFlex="40" class="pl-4" required>
                            <mat-radio-button style="font-size : 11px; margin-left: 10px" value="R">{{'contact.READ' | translate}}</mat-radio-button>
                            <mat-radio-button style="font-size : 11px; margin-left: 10px" value="RW">{{'contact.READ/WRITE' | translate}}</mat-radio-button>
                        </mat-radio-group>
                    </div>
                        <mat-icon title="Ajouter" fxFlex="10" mat-icon-button color="basic" (click)="addDomaines()" style="color:#3c5d80; cursor: pointer">add_circle</mat-icon>
                        <mat-icon *ngIf="form.controls.requested_domains.controls.length > 1" title="Supprimer" fxFlex="10"
                            mat-icon-button color="basic" (click)="deleteRow(i)" style="color:#dd2d2d; cursor: pointer">delete_forever</mat-icon>

                </div>
                <div fxLayout="row wrap" fxLayoutAlign="start center" fxFlex="1 0 auto">
                    <mat-form-field appearance="outline" fxFlex="100" class="pl-4">
                        <mat-label>Message</mat-label>
                        <input matInput formControlName="comment">
                        <mat-icon matSuffix class="secondary-text">message</mat-icon>
                    </mat-form-field>
                </div>
                <div fxLayoutAlign="end center">
                    <button mat-raised-button color="primary" [disabled]="form.invalid" (click)="Envoyer()">{{'contact.Envoyer'
                      | translate }}</button>
                </div>

            </form>
            <pre>{{form.value | json}}</pre> 
        </div>
    </div>
    <ngx-spinner bdColor="rgba(51, 51, 51, 0.8)" size="medium" color="#fff" type="ball-clip-rotate"></ngx-spinner>
</div>

And this my code TS:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
import { Subject } from 'rxjs';
import { FuseTranslationLoaderService } from '@fuse/services/translation-loader.service';
import { locale as english } from 'app/pages/contact/i18n/en';
import { locale as french } from 'app/pages/contact/i18n/fr'
import { User } from 'app/models/user.model';
import { inject } from '@angular/core/testing';
import { AuthService } from 'app/services/auth.service';
import { takeUntil } from 'rxjs/operators';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
    selector: 'app-contact',
    templateUrl: './contact.component.html',
    styleUrls: ['./contact.component.scss']
})
export class ContactComponent implements OnInit {

    form: FormGroup;
    domaines : FormArray;
    user: User;
    domainPattern = /^(?!:\/\/)([a-zA-Z0-9-]+\.){0,5}[a-zA-Z0-9-][a-zA-Z0-9-]+\.[a-zA-Z]{2,64}?$/;
    groupPattern = /^[a-zA-Z_]+$/;
    // Private
    private _unsubscribeAll: Subject<any>;

    /**
     * Constructor
     *
     * @param {FormBuilder} _formBuilder
     */
    constructor(
        private _formBuilder: FormBuilder,
        private _fuseTranslationLoaderService: FuseTranslationLoaderService,
        private _authService: AuthService,
        private cdref: ChangeDetectorRef,
        private toastr: ToastrService,
        private spinner: NgxSpinnerService
    ) {
        // Set the private defaults
        this._unsubscribeAll = new Subject();
        this._fuseTranslationLoaderService.loadTranslations(english, french);
    }
    ngAfterContentChecked() {

        this.cdref.detectChanges();

      }

    // -----------------------------------------------------------------------------------------------------
    // @ Lifecycle hooks
    // -----------------------------------------------------------------------------------------------------

    /**
     * On init
     */
    ngOnInit(): void {
        // Reactive Form
        this.form = this._formBuilder.group({
            firstname: [''],
            lastname: [''],
            email: [''],
            group: ['', Validators.required],
            requested_domains:this._formBuilder.array([this.initItemRows()]),
            comment: ['',],
        });


        this._authService.getAuthStatusListener()
            .pipe(takeUntil(this._unsubscribeAll))
            .subscribe((user) => {
                this.user = user;
                if(user){
                    this.form.patchValue({
                        firstname: user.first_name,
                        lastname:user.last_name,
                        email:user.user_email
                    })
                }

            });
    }

    /**
     * On destroy
     */
    ngOnDestroy(): void {
        // Unsubscribe from all subscriptions
        this._unsubscribeAll.next();
        this._unsubscribeAll.complete();
    }
    get primaryEmail() {
        return this.form.get('email');
    }

    get requested_domains(){
        return this.form.get('requested_domains');
    }

    get group(){
        return this.form.get('group')
    }

    initItemRows() : FormGroup {
        return this._formBuilder.group({
            domain_name: [''],
            right:['']
        });

    }

    Envoyer(){
        const form = this.form.value;
        this.spinner.show();
        this._authService.formulaire(form).subscribe(res => {
            this.spinner.hide();
            this.toastr.success("Your form has been successfully sent");
        },
        error => {
            this.toastr.error("Your form has not been sent");
            setTimeout(() => {
                /** spinner ends after 5 seconds */
                this.spinner.hide();
              }, 1000);
    }
        );
}



    addDomaines() {
        this.domaines = this.form.get('requested_domains') as FormArray;
        this.domaines.push(this.initItemRows());
    }

    deleteRow(index: number) {
        this.domaines.removeAt(index);
      }
}

Please help to resolve this problem and thank you for your time i want to resolve this problem


回答1:


If you disable a field in your form, this field won't be sent in the resulting JSON. If you want to forbid user input but still want the value to be included in your form object, you have to mark the field as readonly:

<input matInput formControlName="lastname" [readonly]="true">

In summary:

Use the readonly attribute to prevent the user from changing the control value, but you still want the value in your form object.

Use the disabled attribute to prevent the user from changing the control value and you don't want the value in your form object.




回答2:


You shouldn't be using disabled with reactive forms. Instead of it, put the logic on the code behind (ts file):

this.form.get('lastname').disable();

// this.form.get('lastname').enable();

Be aware that these methods have optional arguments to control wether you want to fire change event (this.form.get('lastname').valueChanges), which is the default behavior.

About your question (I got it right later on the comments): you can use this.form.getRawValue() to retrieve all fields values (including the disabled ones). Checkout it out on the docs: https://angular.io/api/forms/FormGroup#getrawvalue

Actually, as @jo_va said, maybe the readonly field is more appropriate to get what you want (despite the fact that you cannot control it from the FormControl object).




回答3:


Please add readonly attribute to your input control.

[readonly]="true"


来源:https://stackoverflow.com/questions/55569844/disable-input-on-angular-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!