因为我得到了一个包含许多不同输入字段的表单,为了避免拥有一个巨大的 html 模板,我想将字段数据放在对象中并使用ngFor
.
到目前为止,这是我的代码。
stub.ts - 这是我存储数据的地方
export const MY_DATA = [
{ placeholder: 'First name', name: 'name', model: 'model.name'},
{ placeholder: 'Last name', name: 'lastName', model: 'model.lastName'},
{ placeholder: 'Age', name: 'age', model: 'model.age'}
];
组件.ts
import { Component, OnInit } from '@angular/core';
import {MY_DATA} from './stub';
@Component({
selector: 'app-valutazione-insert',
templateUrl: './valutazione-insert.component.html',
styleUrls: ['./valutazione-insert.component.css']
})
export class ValutazioneInsertComponent implements OnInit {
model: any = {};
data = MY_DATA;
constructor() { }
ngOnInit() {}
submit() {
console.log('Data submitted: ', this.model);
}
}
模板.html
<div id="datiRichiesta" [hidden]="datiRichiestaClicked" >
<div class="form-group" *ngFor="let d of data">
<input type="text" class="form-control" placeholder="{{d.placeholder}}" [(ngModel)]=d.model name="{{d.name}}"
onfocus="this.placeholder = ''" (blur)="this.placeholder = d.placeholder"/>
</div>
</div>
现在,我得到了一些不起作用的东西:
- 即使在呈现的 html 上正确设置了所有属性,占位符值也会采用模型值
- 占位符的行为
onfocus
并且onblur
不起作用 - 最重要的是,如果我尝试提交一些值,这些值不会传递给控制器
现在,如果我使用静态设置所有属性的输入类型,每个问题都会消失。有什么方法可以实现我想要的吗?
谢谢!