【问题标题】:How to get value of input in Angular ( element.setAttribute("[(ngModel)]", "Title" doesn't work)如何在 Angular 中获取输入值( element.setAttribute("[(ngModel)]", "Title" 不起作用)
【发布时间】:2021-12-10 05:38:27
【问题描述】:

我正在尝试获取点击时动态创建的输入的值

这是代码:

Save(form:NgForm){
  const element = document.createElement("input");
  element.setAttribute("type", "text")
  element.setAttribute("placeholder", "Title")
  element.setAttribute("name", "Title")
  element.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)  
}

我试过这个 setAttribute 但没用

element.setAttribute("[(ngModel)]", "Title")

它说:无法在“元素”上执行“setAttribute”:“[(ngModel)]”不是有效的属性名称。

【问题讨论】:

    标签: angular typescript input


    【解决方案1】:

    我不确定我是否理解您尝试这样做的原因。但是,如果您不希望使用任何角度容量,这意味着您没有使用任何带有通过[(ngModel)] 与变量绑定的精心创建的<input> 标签的html 文件,那么您不应 分配[(ngModel)] 和你一样。

    意味着以下内容不起作用,因为它不是 html input 标记中的已知属性。

    element.setAttribute("[(ngModel)]", "Title")
    

    因此,您应该像这样设置值

    element.value = "Title";
    

    小技巧

    在这里,您尝试以 Angular 方式存档的内容
    如果不需要,只需发表评论,我会将其从我的答案中删除

    <!-- app.component.html -->
    <input [(ngModel)]="title" type="text" placeholder="Title" name="Title" 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">
    
    // app.component.ts
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss'],
    })
    export class YourComponent {
      title: string
    
      save() { 
        console.log(this.title)
      }
    }
    

    【讨论】:

    • 感谢您的回答!我尝试了另一种方法,它奏效了!我试图通过单击另一个按钮来获取值,所以我设置了另一个属性 id = 'title' 并且它起作用了: Submit() { const Title = (document.getElementById("title")).value; console.log(标题) }
    【解决方案2】:

    Angular 不能以这种方式工作,您可以创建一个变量(或变量数组)并在 .html 中使用来创建输入。例如

    //in .ts define an object
    inputConfig={type:"text",
                 placeholder:"Title",
                 name:"Title",
                 variable:"title",
                 class="appearance-none ..."
    };
    
    //in .html
    <input [type]="inputConfig.type" [placeholder]="inputConfig.placeholder"
           [name]="inputConfig.name" [ngClass]="inputConfig.class"
           [(ngModel)]="this[inputConfig.variable]">
    

    看看你在 [(ngModel)] this[inputConfig.variable]987654323@中的使用方式

    fool stackblitz

    要获取变量“title”,它只能在 .ts this.title 或 .html title 中使用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      • 2020-03-29
      • 2019-11-29
      • 2019-08-27
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多