angular的formControl值变化不起作用([formControl].valueChanges)不起作用。
创始人
2024-10-24 03:31:32
0次

在Angular中,使用FormControl对象来管理表单控件的值和状态。当使用[valueChanges]绑定来监听FormControl值的变化时,如果发现不起作用,可能是由于以下原因:

  1. 确保FormControl对象已正确创建并绑定到表单控件上:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-my-form',
  template: `
    
  `
})
export class MyFormComponent implements OnInit {
  myControl: FormControl;

  ngOnInit() {
    this.myControl = new FormControl('');
  }
}
  1. 确保订阅[valueChanges]事件:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-my-form',
  template: `
    
  `
})
export class MyFormComponent implements OnInit {
  myControl: FormControl;

  ngOnInit() {
    this.myControl = new FormControl('');

    this.myControl.valueChanges.subscribe(value => {
      console.log(value);
    });
  }
}
  1. 确保在组件的模板中使用了FormsModule或ReactiveFormsModule:
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MyFormComponent } from './my-form.component';

@NgModule({
  imports: [
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [MyFormComponent]
})
export class MyFormModule { }

如果以上步骤都正确无误,但[valueChanges]仍然不起作用,可以尝试使用ChangeDetectorRef来手动触发变化检测:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-my-form',
  template: `
    
  `
})
export class MyFormComponent implements OnInit {
  myControl: FormControl;

  constructor(private cdr: ChangeDetectorRef) { }

  ngOnInit() {
    this.myControl = new FormControl('');

    this.myControl.valueChanges.subscribe(value => {
      console.log(value);
      this.cdr.detectChanges(); // 手动触发变化检测
    });
  }
}

通过这些步骤,你应该能够解决FormControl的值变化不起作用的问题。

相关内容

热门资讯

2027版作弊器!518葫芦岛... 2027版作弊器!518葫芦岛麻将作弊器多功能AI教程,518葫芦岛麻将果然真的是有作弊器教程1、进...
2027版作弊器!蜂娱棋牌作弊... 2027版作弊器!蜂娱棋牌作弊器多功能AI脚本,蜂娱棋牌都是是真的有作弊器脚本2027版作弊器!蜂娱...
2027版透视挂!奥云柳河麻将... 2027版透视挂!奥云柳河麻将透视挂多功能AI脚本,奥云柳河麻将确实是真的有透视挂脚本奥云柳河麻将辅...
2027版作弊器!老友福建麻将... 2027版作弊器!老友福建麻将作弊器多功能AI脚本,老友福建麻将竟然有作弊器脚本该软件可以轻松地帮助...
2027版外挂!推倒胡外挂多功... 2027版外挂!推倒胡外挂多功能AI教程,推倒胡都是是有外挂教程1、打开软件启动之后找到中间准星的标...
2027版透视挂!山西扣点点透... 2027版透视挂!山西扣点点透视挂多功能AI攻略,山西扣点点真是是有透视挂攻略1、进入到山西扣点点是...
2027版作弊器!卡五星作弊器... 2027版作弊器!卡五星作弊器多功能AI插件,卡五星一贯是有作弊器插件1、不需要AI权限,帮助你快速...
2027版作弊器!约战荆门麻将... 2027版作弊器!约战荆门麻将作弊器多功能AI工具,约战荆门麻将其实存在有作弊器工具1、不需要AI权...
2027版透视器!扬帆透视器多... 2027版透视器!扬帆透视器多功能AI脚本,扬帆一直存在有透视器脚本1、点击下载安装,扬帆脚本分类一...
2027版透视器!楚州麻将透视... 2027版透视器!楚州麻将透视器多功能AI技巧,楚州麻将本来是真的有透视器技巧1、让任何用户在无需楚...