angular 2 中的 ngModel 有问题。有一个任务是从组件类中的数组输出几个输入。发现了一种使 ngModel 从 [name] 属性中获取其值而不包含 [()] 中的 ngModel 的可能性。我想知道是否有办法为这些输入提供默认值。
个人详细信息.component.ts :
import {
Component,
} from '@angular/core';
import { Input }from './Input'
@Component({
selector: 'personal-details',
styleUrls: ['personal-details.component.sass'],
templateUrl: 'personal-details.component.html'
})
export class PersonalDetailsComponent {
title: string;
inputs: Input[] = [
new Input('Name', 'text', 'Name', true, true),
new Input('Surname', 'text', 'Surname', true, true),
new Input('Mobile phone Number', 'text', 'phone', true, true),
new Input('Date of Birth', 'text', 'birthday', false, true),
new Input('Title', 'text', 'title', false, false),
new Input('Title after name', 'text', 'title-after-name', false, false),
new Input('Personal number', 'text', 'personal-number', false, false),
new Input('National ID/Passport number', 'text', 'personal-id', false, true),
];
save = function (form) {
console.log(form);
}
constructor(){
this.title = 'someName';
}
}
这是我的模板:
<h4 class="profile__title">Personal Details</h4>
<form #personalDetails="ngForm" (ngSubmit)="save(personalDetails.value)">
<div layout="row" flex-wrap>
<div class="profile__input-wrapper" *ngFor="let input of inputs" flex="33">
<md-input-container class="profile__input-container">
<input md-input
[placeholder]="input.placeholder"
[type]="input.type"
[name]="input.name"
[disabled]="input.isDisabled"
[required]="input.isRequired"
ngModel>
</md-input-container>
</div>
</div>
<profile-footer ></profile-footer>
</form>
尝试了其他几种使用 ngFor 列出它们的方法,但没有成功。
原文由 Mike Kovetsky 发布,翻译遵循 CC BY-SA 4.0 许可协议
直接的方法是将 ngModel 与单向绑定一起使用
它会将初始值传递给输入,而不会对事件做出反应并将更改传递回模型。