角形控件值更改不起作用 [英] Angular Form Control valueChanges not working

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

问题描述

如果通过订阅进行更改,我想获取我的一个表单(家庭)值,但是这似乎有问题,因为控制台日志上什么也没有。

I want to get one of my forms ("family") value if changed by subscribe but it seems something 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: `<h1>Hello World!</h1>
            <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));
}

这篇关于角形控件值更改不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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