简体   繁体   中英

How to get the prev/next array string in Angular

What I have :Now in my program, there is a previous and next button, whenever I click the button the {{departmentID}} in array will +1 or -1.

For example, the current {{departmentName}} ,{{departmentID}} is Node,2 , after I click Next button the result will become Node,3 .(Only the ID itself is change)

What I want : When I click the Next button the result will change from Node,2 >> Ruby,3 which is from 2nd array to 3rd array.

What I tried :Directly +1 in let previousName = this.departmentName+1; but surely it wont work because string cant +1 like that and I get null value.

Department Array

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]);

}

Convert the string into number in this way

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;

  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM