【问题标题】:Use Angular /typsecript correctly to fill an array with selected objects正确使用 Angular /typescript 用选定的对象填充数组
【发布时间】:2020-03-02 09:46:25
【问题描述】:

我有一个角度应用程序从 spring-boot rest api 读取 json 资源(简单播放器对象的集合 - id、名称、位置、值...)....我有一个按钮,每个简单显示的对象都在 UI 上,当用户单击component.html上的购买按钮时,我只想将每个对象存储在数组中......我需要使用我的component.ts文件,而且我是打字稿的新手,我不确定如何链接html方法调用.ts逻辑页面...

任何帮助都非常感谢大家......这只是我的基本幻想足球类型应用程序的第二阶段,其中列表(如果我在 java 中,则为数组列表)将代表用户选择购买的球员/他们的自定义团队...... ..

组件.HTML: '

     <ul *ngIf="Ballers">

      <li *ngFor="let player of Ballers">
        <p class="name">{{player.name}}</p>
        <p class="position">{{player.position}}</p>
        <p class="value">£{{player.value}} m</p>
        <button class="buyButton" on-click="buyThisPlayer()">Add to Squad</button>
     </li>
   </ul>
  </div>

组件.TS:

 @Component({
    selector: 'app-player-list',
    templateUrl: './playerList.component.html',
    styleUrls: ['./playerList.component.scss']
 })
export class PlayerListComponent implements OnInit {

  Ballers: Object;
 // let selectedKickers=[] ;   //to declare my empty array???

   constructor(private httpService: HttpService) { }

  ngOnInit() {
      this.httpService.getPlayers().subscribe(data => {
        this.Ballers = data;
        console.log(this.Ballers);
      })
  }

  buyThisPlayer(){
   selectedKickers.push(this); // this seems the only way to pinpoint my object to add???
  }

}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    如果你只是对点击处理程序感兴趣,你可以在方法中传递播放器并像这样绑定到它:

    <button class="buyButton" (click)="buyThisPlayer(player)">Add to Squad</button>
    
    @Component({
        selector: 'app-player-list',
        templateUrl: './playerList.component.html',
        styleUrls: ['./playerList.component.scss']
     })
    export class PlayerListComponent implements OnInit {
    
      Ballers: any;
      selectedPlayers: any[] = [];
    
       constructor(private httpService: HttpService) { }
    
      ngOnInit() {
          this.httpService.getPlayers().subscribe(data => {
            this.Ballers = data;
            console.log(this.Ballers);
          })
      }
    
      buyThisPlayer(player){
       this.selectedKickers.push(player);
      }
    

    我会提出其他建议(深入了解角度最佳实践)。如果您有兴趣,请告诉我。

    【讨论】:

    • 干杯,太完美了,它让我进入下一个垫脚石......现在将我选择的玩家列表挂回我的 api 并创建一个数据库条目......向前和向上。 ..
    猜你喜欢
    • 2017-01-28
    • 2022-10-01
    • 2018-10-17
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多