首页 > 解决方案 > 如何在Angular中获取上一个/下一个数组字符串

问题描述

我所拥有的:现在在我的程序中,有一个上一个和下一个按钮,每当我单击按钮时,数组中的 {{departmentID}} 将 +1 或 -1。

例如,当前的 {{departmentName}} ,{{departmentID}} 是Node,2,点击Next按钮后结果会变成Node,3。(只有 ID 本身是变化的)

我想要什么:当我单击 Next 按钮时,结果将从Node,2 >> Ruby,3更改为从第二个数组到第三个数组。

我尝试了什么:直接+1,let previousName = this.departmentName+1;但肯定不会起作用,因为字符串不能像那样+1,我得到空值。

部门阵列

departments = [
    {"id":1,"name":"Angular"},
    {"id":2,"name":"Node"},
    {"id":3,"name":"Ruby"},
  ]

HTML:

<h3>
     you selected department with id = {{departmentName}},{{departmentID}}
    <p class="click"> <button (click)="goPrevious()">Previous</button>
   <button (click)="goNext()">Next</button>
    </h3>

在此处输入图像描述

export class DepartmentDetailComponent implements OnInit {
  public departmentID;
  public departmentName;

  constructor(private route : ActivatedRoute,private router: Router) { }

  ngOnInit() {
      this.route.paramMap.subscribe((params:ParamMap) => {
        let id = parseInt(params.get('id'));
        let name = params.get('name');

        this.departmentID = id;
        this.departmentName = name;

      });
    }

goPrevious(){
  let previousId = this.departmentID-1;
  let previousName = this.departmentName; // here is the code to change the departmentName when I click previous button.
 this.router.navigate(['/departments-list',previousId]);

}

标签: javascriptangular

解决方案


用这种方式将字符串转换为数字

ngOnInit() {
  //let id = parseInt(this.route.snapshot.paramMap.get('id'));
  //this.departmentID = id;
  this.route.paramMap.subscribe((params:ParamMap) => {
  this.id = +params['id'];  // (+) converts string 'id' to a number      
    let name = params.get('name');

    this.departmentID = id;
    this.departmentName = name;

  });
}

推荐阅读