Angular FormControl valueChanges不起作用 [英] Angular FormControl valueChanges doesn't work

查看:82
本文介绍了Angular FormControl valueChanges不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要通过订阅进行更改,我想获得表单("family")值之一,但这似乎是错误的,因为控制台日志上什么也没有.

I want to get one of my forms ("family") value if changed by subscribing but it seems something is wrong because I got nothing on my console's log.

import { Component , AfterViewInit } from '@angular/core';
import {FormGroup,FormBuilder} from '@angular/forms';
import {Observable} from 'rxjs/Rx';

@Component({
  selector: 'app-root',
  template: `<form [formGroup]="frm1">
<input type="text" formControlName="name" >
<input type="text" formControlName="family">
</form>
`,

})

export class AppComponent implements AfterViewInit{
  frm1 : FormGroup;

  constructor( fb:FormBuilder){
    this.frm1 = fb.group({
      name : [],
      family: []
    });
  }
  ngAfterViewInit(){
    var search = this.frm1.controls.family;
    search.valueChanges.subscribe( x => console.log(x));
  }
}

推荐答案

在表单变量 frm1 上使用 get 方法.并使用 ngOnInit()代替 ngAfterViewInit()

Use get method on form variable frm1. And use ngOnInit() instead of ngAfterViewInit()

ngOnInit() {  
   this.frm1.get('family').valueChanges.subscribe( x => console.log(x));
}

这篇关于Angular FormControl valueChanges不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆