如何在HTML代码中访问FormControl值

时间:2019-07-06 10:53:46

标签: angular typescript angular-material

我正在以编程方式更改“选择”格式的值。

在表单字段中,您可以看到该值已更改。但是元素"p"仍然是隐藏的。

如果您手动更改表单的值,则元素“ p”的可见性将正常工作。

  

预期结果:

The <p> tag should be visible if the value of `field1` FormControl is equal to `1`.

请告诉我,可能是什么问题?

component.html

<form [formGroup]="formGroup">
  <mat-form-field class="mb-4" fxFlex="100">
      <mat-select #field1 formControlName="field1" placeholder="Data type" required>
        <mat-option value="0" selected>Boolean</mat-option>
        <mat-option value="1">Int</mat-option>
        <mat-option value="2">Double</mat-option>
        <mat-option value="3">String</mat-option>
        <mat-option value="4">Byte array</mat-option>
        <mat-option value="5">Object</mat-option>
      </mat-select>
    </mat-form-field>
</form>

<p *ngIf="field1.value === '1'">Integer</p>

<button mat-raised-button color="primary" (click)="onClick()">Set 'Int'</button>

component.ts

export interface Item {
  value: string;
  viewValue: string;
}

@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
  public data: Item[] = [
    {value: '1', viewValue: 'Option 1'},
    {value: '2', viewValue: 'Option 2'},
    {value: '3', viewValue: 'Option 3'}
  ];
  public formGroup: FormGroup;

  constructor(private _formBuilder: FormBuilder){

  }

  ngOnInit() {
    this.formGroup = this._formBuilder.group({
      field1: [1, null]
    });
  }

  onClick(){
    this.formGroup.controls.field1.setValue('1');
  }
}

Example Stackblitz

1 个答案:

答案 0 :(得分:0)

代替#template reference变量,您可以使用:

formGroup.controls['field1'].value

所以是HTML代码:

<p *ngIf="formGroup.controls['field1'].value === '1'">Integer</p>