Html 将项目添加到赢得';添加新项目时不会更改

Html 将项目添加到赢得';添加新项目时不会更改,html,angular,typescript,Html,Angular,Typescript,我有一个简单的输入栏,可以在其中键入要添加到列表中的新项。但是,当我添加一个新项目时,它将替换前面添加的数据,并按正常方式更新列表 用于添加行星的函数如下:(.service) 在组件中,它如下所示: newPlanet: Planet = {} as Planet; addPlanet(): void { this.planetService.addPlanet(this.newPlanet) } html如下所示: <h1>Create a Planet</

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

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

在组件中,它如下所示:

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>
创建一个行星
创造
行星列表
    {{planet.name}}:{{{planet.description}X
我遗漏了什么吗?

检查一下这个StackBlitz:

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>

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

您需要在服务中使用可观察对象,并将其包含在组件中以检测更改。您如何在中初始化
planets
service@Sujay... 我在服务中得到了如下数组:planets:PLanet[]=[{name:'the PLanet name',description:'which the PLanet is about'}];我在我的服务文件中插入了我的行星阵列。我所需要添加的只是更新我的onInit()中的addPlanet功能。你的方法也很好,谢谢你的反馈。
<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>
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);
    }
  }
}