目前我正在 Angular 17 中试验模板驱动表单,我有对象接口
interface test2 = {
name : string
}
interface test = {
name : string,
another? : test2
}
我正在创建像
这样的对象let obj : test = { name: "moo", another: null };
然后在页面中我有一个简单的输入
<input name="tester" [(ngModel)]="obj.another.name">
这会崩溃并燃烧。正在做
<input name="tester" [(ngModel)]="obj.another && obj.another.name">
将允许其显示页面,但在将数据输入字段时不创建对象。 Angular 是否可以在对象为 null 时创建 test2 的对象,并在字段中输入数据时分配其值?这曾经在 AngularJS 中工作。
这将允许我将对象设置为空,除非有人输入了数据。
干杯
你可以这样做:
<input name="tester" [ngModel]="obj.another?.name"
(ngModelChange)="obj.another = $event ? { name: $event } : null">
此外,您可能需要将
another? : test2
更改为 another? : test2 | null
。