Home > front end >  How to get value of input in Angular ( element.setAttribute("[(ngModel)]", "Title&quo
How to get value of input in Angular ( element.setAttribute("[(ngModel)]", "Title&quo

Time:10-25

I am trying to get the value of a dynamically created input on click

this is the code :

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)  
}

I tried this setAttribute but it didn't work

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

it says: Failed to execute 'setAttribute' on 'Element': '[(ngModel)]' is not a valid attribute name.

CodePudding user response:

I'm not sure I understand the reason why you're trying to doing that. But if you whish to not use any angular capacity, meaning that you aren't using any html file with nicely created <input> tags bound with variable through [(ngModel)], then you shall not assign [(ngModel)] like you do.

Meaning the following isn't working, because it isn't a known attribute from the html input tag.

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

For that reason you should set the value like this

element.value = "Title";

Small tips

Here, what you're trying to archive in an Angular manner
if not required, just comment and I'll remove it from my answer

<!-- 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)
  }
}

CodePudding user response:

Angular not works in this way, you can create a variable (or an array of variables) and use in the .html to create the input. e.g.

//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]">

See how you use in [(ngModel)] this[inputConfig.variable]

a fool stackblitz

To get the variable "title" it's only use in .ts this.title or in .html title

  • Related