0

I have the following in HTML

  <mat-form-field [appearance]="matFormFieldAppearance" style="margin-left:10px;width:50%">
    <mat-label>Type</mat-label>
    <mat-select formControlName="TypeId" required>
      <mat-option *ngFor="let item of TypeList" [value]="item.Id">
        {{item.Title}}
      </mat-option>
    </mat-select>
  </mat-form-field>


  <mat-form-field [appearance]="matFormFieldAppearance" style="margin-left:10px;width:50%">
    <mat-label>Category</mat-label>
    <mat-select formControlName="CategoryeId" required>
      <mat-option *ngFor="let item of CategoryList" [value]="item.Category">
        {{item.Category}}
      </mat-option>
    </mat-select>
  </mat-form-field>

In TypeScript, MatDialog receives data and if Field1 is not null then, I want the form fields be put in ReadOnly

this.K = this.matdialogData;
if (this.K.Field1 !== null)
{
          this.myForm.controls.CategoryeId.ReadOnly(); //Something like this
          this.myForm.controls.TypeId.ReadOnly();//Something like this
}
1
  • Are you trying to disable the input controls? It is not clear what exactly you are looking for. Commented Sep 20, 2020 at 12:43

2 Answers 2

2

You can disable the fields to make them read-only.

this.myForm.controls.CategoryeId.disable();
this.myForm.controls.TypeId.disable();

Also, you can add a class to mat-form-field with style pointer-events-none to make the fields read-only.

Sign up to request clarification or add additional context in comments.

3 Comments

I get the warning. It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors. Example: form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.required), last: new FormControl('Drew', Validators.required) });
I have <mat-icon matChipRemove>cancel</mat-icon> to which I am unable to mention disabled(); It throws error.
It is suggesting you to use disabled in the form control.You can try using FormControl({value: '' ", disabled: this.K.Field1}) where you define the form control in the component.For mat-icon you can add a class with pointer-events-none to make the it read-only.
1

Try this:

this.myForm.controls['CategoryeId'].disable();
this.myForm.controls['TypeId'].disable();

1 Comment

Note that setting a form control as disabled will ignore the validators. In order to keep the validators and make it not editable, its better to use the readonly attribute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.