将项目添加到添加新项目时不会更改的列表

时间:2018-09-06 08:04:37

标签: html angular typescript

我有一个简单的输入栏,可以在其中输入要添加到列表中的新项目。但是,当我添加新项目时,它将替换之前添加的数据并正常更新列表。

用于添加行星的函数如下:(.service)

addPlanet(planet: Planet) {
    if(planet.name && planet.description) {
    this.planets.push(planet);
    }
  }

在组件中,如下所示:

newPlanet: Planet = {} as Planet;

addPlanet(): void {
    this.planetService.addPlanet(this.newPlanet)
  }

html如下:

<h1>Create a Planet</h1>
<input [(ngModel)]="newPlanet.name" type="text" placeholder="new name...">
<input [(ngModel)]="newPlanet.description" type="text" placeholder="new desription here...">
<button type="button" (click)="addPlanet(newPlanet)">Create</button>
<h1>Planet Listings</h1>
<ul>
  <li *ngFor = "let planet of planets"><b>{{planet.name}}:</b> {{planet.description}}<button type="button" class="ml-2" (click)="removePlanet(planet)">X</button></li>
</ul>

我想念什么吗?

1 个答案:

答案 0 :(得分:0)

检查此StackBlitz:List of planets

HTML文件:

<h1>Create a Planet</h1>
<input [(ngModel)]="name" type="text" placeholder="new name...">
<input [(ngModel)]="description" type="text" placeholder="new desription here...">
<button type="button" (click)="addPlanet(name, description)">Create</button>
<h1>Planet Listings</h1>
<ul>
  <li *ngFor = "let planet of planets"><b>{{planet.name}}:</b> {{planet.description}}</li>
</ul>

TS文件:

interface Planet {
  name: string,
  description: string
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  planets: Planet[] = [];
  name: string;
  description: string;

  addPlanet(name, description) {
    let planet: Planet = {
      name: name,
      description: description,
    } as Planet;

    if(planet.name && planet.description) {
      this.planets.push(planet);
    }
  }
}

问题在于,您在[(ngModel)]指令中直接绑定了插入数组中的最后一个对象(newPlanet)。