Home > database >  Angular Updating an Input Field
Angular Updating an Input Field

Time:10-10

In my app, I have two input fields. One is a mat-option field and the other one is a regular input field. What I want is that when I select an option from the mat-option field (Supplier), I want that option to appear in the regular input field (Subject). The code I've written so far is below. Right now, I couldn't make it work. What should I do?

HTML:

<mat-form-field appearance="outline" fxFlex="100" fxFlex.gt-xs="30" class="w-100-p"
                        ngClass.gt-xs="pr-4">
                        <mat-label>Supplier</mat-label>
                        <mat-select formControlName="Supplier">
                            <mat-option *ngFor="let sp of supplierList" [value]="sp">
                                {{sp.SupplierName}}
                            </mat-option>
                        </mat-select>
                        <mat-icon matSuffix class="secondary-text">person</mat-icon>
                    </mat-form-field>
                </div>
                <div fxLayout="row" fxLayoutAlign="start center">
                    <mat-form-field appearance="outline" fxFlex fxFlex.gt-xs="60">
                        <mat-label>Subject</mat-label>
                        <input matInput formControlName="Subject" maxlength="150" required 
                        >
                        <mat-icon matSuffix>short_text</mat-icon>
                    </mat-form-field>
                </div>

TS:

ngOnInit(): void {
    // Reactive Form
    this.form = new FormGroup({
        Subject: new FormControl("", [
            Validators.required,
            Validators.maxLength(150),
        ]),
        Supplier: new FormControl(
            this.previousReqest ? this.previousReqest.Supplier : "",
            Validators.required
        ),
    });

    this.form.controls["Supplier"].valueChanges
    .subscribe(data => {
      this.form.controls['Subject'] = data;
    });

    if (
        UserInformation.userAuthorizedRoutes &&
        UserInformation.userAuthorizedRoutes.length > 0
    ) {
        this.userRights = UserInformation.userAuthorizedRoutes.filter((x) =>
            new RegExp(x.Action).test(this._router.routerState.snapshot.url)
        )[0];
    }

    this.initializeUserSettings();
}

CodePudding user response:

You can subscribe to valueChanges event at the time of initialisation.

this.form.controls["Supplier"].valueChanges
    .subscribe(data => {
      if(data){
       this.form.controls['Subject'].setValue(data.SupplierName);
      }
    });

CodePudding user response:

this.form.get('Subject').value is read-only, if you want to set a value to a form control you should use .setValue(value), can you try this and see if it works:

this.form.get('Subject').setValue(data)
  • Related