Add DOM element on Button click with Angular 2+

2020-07-18 23:29发布

问题:

Hi I'm learning how to manipulate the DOM with Angular 2+ and I want to add an Input field with type email when the click event is triggered. I've researched a bit with google, but couldn't find a soluion with Angular2+.

<form>
<fieldset>
  <legend>
    <span class="number">3</span>E-Mail Receipants</legend>
  <input type="email" name="email1" placeholder="E-Mail Recipients john.doe@mail.com">
  <input type="button" value="Add E-Mail" (click)="addInputEmail()">
</fieldset>
<input type="submit" value="Generate Template" />

How can I generate extra inpult fields under the already existing one? What are my tools to use?

addInputEmail(){
}

On each button click a new input field should be generated. Im kinda hopeless because I don't know what 'Tools' I have to manipulate it in the first place.

Thanks.

回答1:

Something like this should work --

 <div *ngFor='let email of emails'>
   <input type="email" [attr.name]="email" >
 </div>
 <input type="button" value="Add E-Mail" (click)="addInputEmail()">

--

export class formComponent {
  emails = ["email1"];
  emailNumber = 1;
  constructor () {

  }

  addInputEmail() {
    this.emailNumber++; 
    this.emails.push("email"+this.emailNumber)
  }
}

Hope this makes sense.

You are building the input elements based on the array of emails. And on the button press you add to the array which creates a new input in the template.