以角度形式获取 [对象] ,并且还将下拉列表(选择)设置为默认值0索引。在编辑的情况下一切正常。我是否需要为此创建页面初始化模型属性?
修改: ngModelChange 未调用 doNameChange 函数。
组件:
export class User {
Id: number;
Name: string;
Gender: string;
}
this.user = {
Id: 0,
Name: '',
Gender: ''
}
doNameChange(event) {
debugger;
console.log(event); // logs model value
}
HTML
<form (ngSubmit)="save(f.value, f.valid)" #f="ngForm" novalidate materialize>
<input id="Name" (ngModelChange)="doNameChange($event)" name="Name" #Name="ngModel" type="text" class="validate form-control" required minlength="3" [(ngModel)]="user.Name">
<select id="Gender" name="Gender" #Gender="ngModel" class="validate form-control" [(ngModel)]="user.Gender" required>
<option value="">-- Select Gender --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</form>
答案 0 :(得分:1)
使用反应形式时,请勿使用适用于基于模板的表单的ngModel。 如果您需要听取更改:
ngÒnInit(){
this.employeeForm = this._fb.group({
EmployeeId: 0,
Name: ['', [Validators.required, Validators.minLength(3)]],
Gender: ['', [Validators.required]] //dropdown
});
this.onChanges();
}
...
onChanges(): void {
this.myForm.valueChanges.subscribe(val => {
console.log(val);
});
}
//or:
onChanges(): void {
this.myForm.get('name').valueChanges.subscribe(val => {
console.log(val);
});
}