Angular如何获取动态创建input的值?setAttribute绑定[(ngModel)]报错
问题原因
[(ngModel)] 是Angular专属的模板语法糖,不属于原生HTML的合法属性,你用原生DOM API的setAttribute方法设置该属性时,浏览器无法识别,所以会抛出属性名不合法的报错。而且原生方式创建的DOM元素不会被Angular的变更检测体系接管,就算你硬写上去这个属性,双向绑定也不会生效。
解决方案
方案一:直接用原生API取值(最简单,适合轻量场景)
你不需要强行绑定ngModel,直接在需要取值的时候获取对应DOM元素的value即可:
首先修改你的创建代码,删掉错误的ngModel绑定行:
Save(form:NgForm){ const element = document.createElement("input"); element.setAttribute("type", "text") element.setAttribute("placeholder", "Title") element.setAttribute("name", "Title") // 删掉错误的 setAttribute("[(ngModel)]", "Title") 行 element.setAttribute("class","appearance-none block w-full bg-white text-gray-700 border border-gray-400 shadow-inner rounded-md py-3 px-4 leading-tight focus:outline-none focus:border-gray-500"); document.getElementById("title").appendChild(element) }
需要取输入值的时候直接调用如下代码即可:
// 拿到输入框的值 const titleValue = (document.querySelector('input[name="Title"]') as HTMLInputElement).value;
方案二:使用Angular原生动态组件能力实现双向绑定(适合复杂表单场景)
如果你需要完整使用Angular的表单能力和双向绑定,不要直接操作原生DOM,改用Angular提供的ViewContainerRef来动态插入带input的组件,即可正常使用ngModel绑定。
步骤1:创建动态输入子组件
新建dynamic-input.component.ts:
import { Component, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'app-dynamic-input', template: ` <input type="text" placeholder="Title" name="Title" [(ngModel)]="inputValue" (ngModelChange)="onValueChange($event)" class="appearance-none block w-full bg-white text-gray-700 border border-gray-400 shadow-inner rounded-md py-3 px-4 leading-tight focus:outline-none focus:border-gray-500" >` }) export class DynamicInputComponent { inputValue = ''; @Output() valueChange = new EventEmitter<string>(); onValueChange(val: string) { this.valueChange.emit(val); } }
步骤2:父组件中插入动态组件
首先在父组件模板中添加插入容器:
<div #titleContainer id="title"></div>
父组件ts代码:
import { Component, ViewChild, ViewContainerRef } from '@angular/core'; import { NgForm } from '@angular/forms'; import { DynamicInputComponent } from './dynamic-input.component'; @Component({ // 你的原有组件配置 }) export class YourParentComponent { @ViewChild('titleContainer', {read: ViewContainerRef}) titleContainer!: ViewContainerRef; Title = ''; Save(form: NgForm) { this.titleContainer.clear(); // 创建动态组件实例 const compRef = this.titleContainer.createComponent(DynamicInputComponent); // 订阅输入值变化,同步到本地变量 compRef.instance.valueChange.subscribe(val => { this.Title = val; }); } }
这样就可以正常通过this.Title拿到输入框的双向绑定值了。
内容的提问来源于stack exchange,提问作者intheCT
相关产品推荐
相关产品推荐

