【发布时间】:2020-03-16 19:53:51
【问题描述】:
我正在尝试在 Angular 中使用 NGForm,但我不明白的是使用 ngForm 控件
谢谢
stackblitz:https://stackblitz.com/edit/angular-gt66nu
这是一个例子:
app-component.html
<form name="form" #f="ngForm">
<div>
<label>name</label>
<input name="name" [(ngModel)]="model.name">
</div>
<div>
<label>surname</label>
<input name="surname" [(ngModel)]="model.surname">
</div>
</form>
app-component.ts
import { Component, AfterViewInit,ViewChild } from '@angular/core';
import {NgForm} from '@angular/forms'
@Component({
selector: 'my-app',
templateUrl: 'app.component.html'
})
export class AppComponent implements AfterViewInit {
model: any = {};
oldForm;
@ViewChild('f', {static: false}) form: NgForm
onSubmit() {
alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.model))
}
ngAfterViewInit() {
this.oldForm = this.form.controls
console.log('form: ',this.form);
this.form.form.valueChanges.subscribe( item => {
console.log('item: ' ,item);
})
}
}
【问题讨论】:
-
有什么问题?