我希望获得我的一个表单(“系列”)值,如果通过订阅更改但似乎有问题,因为我的控制台日志中没有任何内容。
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));
}
}
答案 0 :(得分:4)
在表单变量get
上使用frm1
方法。并使用ngOnInit()
代替ngAfterViewInit()
ngOnInit() {
this.frm1.get('family').valueChanges.subscribe( x => console.log(x));
}
答案 1 :(得分:2)
试试这个:
import { Component , AfterViewInit, OnInit } 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, OnInit{
frm1 : FormGroup;
constructor( private formBuilder: FormBuilder){}
ngOnInit(): void {
this.formInit();
this.formSet();
}
formInit(): void {
this.frm1 = this.formBuilder.group({
name: [''],
family['']
})
}
formSet(): void {
const editForm = {
name: 'test-name',
family: 'test familty',
};
this.frm1.patchValue(editForm)
}
ngAfterViewInit(){
this.frm1 .controls.family.valueChanges.subscribe(
() => {
console.log(this.frm1 .controls.family.value)
}
)
}
}