【问题标题】:Angular 2 Reactive Forms - Detect input change event on componentAngular 2 Reactive Forms - 检测组件上的输入更改事件
【发布时间】:2017-11-11 15:32:56
【问题描述】:

我想检测 form.component.ts 上输入的 change 事件的值。 我不想调用函数 ex: (onChange) = "function($event.target.value)"

public form: FormGroup;

constructor(private formBuilder: FormBuilder){ 

}

private loadForm(){
    this.form = this.formBuilder.group({
        tipo: [null, Validators.required],
        nomeRazao: [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(64)])],
        apelidoFantasia: [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(64)])],
        cpfCnpj: [null, Validators.compose([Validators.required, Validators.minLength(11), Validators.maxLength(14)])],
        rgIe: [null],
        contato: this.formBuilder.group({
            email: [null],
            telefone: [null]
        }),
        endereco: this.formBuilder.group({
            cep: [null, Validators.pattern('^([0-9]){5}([-])([0-9]){4}$')],
            uf: [null],
            cidade: [null],
            bairro: [null, Validators.required],
            logradouro: [null],
            complemento: [null],
            numero: [null, Validators.pattern('/^\d+$/')]
        })
    });
}

ngOnInit() {
    this.loadForm();
}

【问题讨论】:

    标签: angular2-forms


    【解决方案1】:

    您可以使用以下方式订阅您的表单更改:

    this.form.valueChanges.subscribe(() => {
       if (this.registerForm.controls['yourControlName'].value === 'someValue') {
          // 
       }
     });
    

    【讨论】:

    • 很好的答案,但更好的类型安全是:this.form.valueChanges.subscribe((data) => { if (data.yourControlName === 'someValue') { // } } );
    【解决方案2】:

    为了检测特定字段的值变化,可以订阅该字段的'valueChanges'事件,如下所示:

    this.myForm.get('formcontrolname').valueChanges.subscribe(val => {
        this.message = val;
      });
    

    【讨论】:

    • 你能多说一些吗,在哪里包含这个sn-p?实际上我必须检测动态表单的复选框的变化。
    • @SaurabhSinghRajput 将其放入 ngOnInit()
    • 这是一个很好的链接,但正如 Tom Stickel 提到的,把它放在 ngOnInit 而不是 ngOnChanges 中:alligator.io/angular/reactive-forms-valuechanges
    猜你喜欢
    • 2019-11-23
    • 2016-12-13
    • 2018-08-24
    • 1970-01-01
    • 2023-03-04
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    相关资源
    最近更新 更多