Angular2 - 使用click事件添加项目

时间:2016-11-23 21:51:19

标签: angular onclick

我知道以前有人问过,但我发现的最佳答案是9个月前:here并且无法使用新角度

我想将change或任何其他项目推送到我的HTML,只需点击angular2即可。

我该怎么做?

我想在新的角度

中重新创建this plunker

2 个答案:

答案 0 :(得分:0)

我认为这就是你正在寻找的东西:

import { Component } from '@angular/core';

class ContactInfo {
  constructor(public description: string) {}
}

@Component({
  selector: 'my-app',
  template: `
  <ul>
    <li *ngFor="let info of information">
      <pre>{{ info.description }}</pre>
    </li>
  </ul>

  <input #newInfo (keyup.enter)="addInfo(newInfo.value)" (blur)="addInfo(newInfo.value); newInfo.value='' ">

  <button (click)="addInfo(newInfo.value)">Add</button>
  `
})
export class AppComponent {
  information = [
    new ContactInfo('HTML5 = Regards DOM'),
    new ContactInfo('CSS3 = Regards DOM styling')
  ];

  addInfo(newInfo: string) {
    if (newInfo) {
      this.information.push(new ContactInfo(newInfo));
    }
  }
}

http://plnkr.co/edit/8SSAa0mEK9YB1IxIHaoK

答案 1 :(得分:0)

试试这个:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
import { Component } from '@angular/core';

class ContactInfo {
  constructor(public description: string) {}
}

@Component({
  selector: 'my-app',
  template: `
  <ul>
    <li *ngFor="let info of information">
      <pre>{{ info.description }}</pre>
    </li>
  </ul>
  
  <input #newInfo (keyup.enter)="addInfo(newInfo.value)" (onclick)="addInfo(newInfo.value); newInfo.value='' ">
  
  <button (click)="addInfo(newInfo.value)">Add</button>
  `
})
export class AppComponent {
  information = [];
  
  myInfo = this.information[0];
  
  addInfo(newInfo: string) {
    if (newInfo) {
      this.information.push(new ContactInfo(newInfo));
    }
  }

}