Angular Reactive Form值无法正常工作?

时间:2018-01-29 16:24:36

标签: angular typescript

我用控件的布尔值创建了Angular Reactive Form。我需要从幻灯片切换控件中获取值并解决条件。它看起来很简单但在我的代码中结果总是错误的。

createForm() {
        this.threatForm = this.fb.group({
        threatId: 0,
        name: ['', [Validators.required]],
        category: [1, [Validators.required]],
        description: [''],
        internalExternal: [1, [Validators.required]],
        securitySafety: [3, [Validators.required]],
        avoidRisk: [],
        shareRisk: [],
        reduceRisk: [],
        acceptRisk: [],
        confidenciality: [false],
        integrity: [false],
        availability: [false],
        authenticity: [false],
    })
}

ngOnInit() {
    this.onGetThreatsCategory();

    if (this.threatForm.value.avoidRisk === true) {
        console.log("Risk value: TRUE")
    }

    else {
        console.log("Risk value: FALSE")
    }
}

当我在HTML中打印值时,我得到了很好的结果,

  AvoidRisk: {{ this.threatForm.controls.avoidRisk.value | json }}

但每次TypeScript值都为FALSE。

2 个答案:

答案 0 :(得分:1)

问题是您尝试检查ngOnInit方法中的值,但是您正在将avoidRisk的表单控件初始化为假值。此外,在检查特定控件的值之前,您没有构建表单,因此总是会出错。

首先,您需要为avoidRisk提供一个默认值true(假设您希望它在OnInit生命周期钩子中为真,如您的示例所示):

createForm() {
  this.threatForm = this.fb.group({
    threatId: 0,
    name: ['', [Validators.required]],
    category: [1, [Validators.required]],
    description: [''],
    internalExternal: [1, [Validators.required]],
    securitySafety: [3, [Validators.required]],
    avoidRisk: [true], // give it the initial value of true
    shareRisk: [],
    reduceRisk: [],
    acceptRisk: [],
    confidenciality: [false],
    integrity: [false],
    availability: [false],
    authenticity: [false],
  })
}

然后在ngOnInit方法中,在检查表单的值之前创建表单。现在,您可以在表单控件上订阅valueChanges属性,该属性将返回其Observable的值。

ngOnInit() {
  this.createForm(); // create the form

  /* subscribe to your form control's value */
  this.threatForm.get('avoidRisk').valueChanges.subscribe(value => {
    if (this.threatForm.get('avoidRisk').value === true) {
      console.log('Risk value: TRUE');
    } else {
      console.log('Risk value: FALSE');
    }
  });
}

答案 1 :(得分:0)

要从表单控件this.threatForm.get('avoidRisk').value获取值,您可以将其用作

if (this.threatForm.get('avoidRisk').value === true) { ... } else { ... }

和html,

{{threatForm.get('avoidRisk').value}}