Angular - 用于输入的动态 ngModel

时间:2021-06-08 09:48:41

标签: angular

如何为表单元素(即输入、选择)创建动态模型?

我有这个:

<input type="text" [name]="input.name" [(ngModel)]="input.name" [title]="input.title" /> 

其中模型可以是动态生成的任何内容(即地址、名字)?

export class SampleComponent implements OnInit {

    inputs!:any[];

    constructor() { }

    ngOnInit(): void {

        console.log(this.inputs);

    }

}

我寻找相关问题,这是最接近 Set a dynamic property in ngModel inside ngFor, with Angular 2 的问题,但我似乎可以解决问题。还有其他方法可以实现吗?

角度版本:(12.0.2)

提前致谢!enter code here

2 个答案:

答案 0 :(得分:1)

您最好使用 Reactive Forms 而不是 Template Driven 表单来完成此任务,因为当涉及到动态验证器和多个工作示例(包括this one 在官方文档上)。

由于您的模型具有 any 类型,因此这几乎可以回答您的问题 - 在我看来无需重复官方文档(尽管如果您使用 Google "angular dynamic form",还有多个其他有效示例。

>

答案 1 :(得分:1)

#I guess you might look at this
https://angular.io/guide/forms#bind-input-controls-to-data-properties

#import FormsModule

#create a template driven form
<form #myForm="ngForm">
<input type="text" class="form-control" id="name"
               required
               [(ngModel)]="input.name" name="input.name"
[title]="input.title"
               #name="ngModel">
<!-- for example -->
<select class="form-control" id="cities"
                required
                [(ngModel)]="model.city" name="cities"
                #cities="ngModel">
          <option *ngFor="let data of data" [value]="data">{{data}}</option>
        </select>
</form>
# here #cities, #name is just template ref variable can be used or avoided in case you don't need to track control of model
相关问题