简体   繁体   中英

Dynamic routerLink in Angular

I have a list, which contains strings and in this list I use *ngFor no problem. I use index in ngFor to determine which route to go, but i discovered the flaws in this design, so i want to change it. in the list component i have a string array, just like the list items. how can i route to this list's content using indexes.

my curent code is like this:

<div class="col-md-12">
        <ul class="list-group">
            <a 
            class="list-group-item"
            routerLinkActive="active"
            style="cursor: pointer;"
            [routerLink]="[i]"
            *ngFor="let l of list; let i = index" >
                {{ l }}
            </a>
        </ul>
        
    </div>

I want to achive something like this:

<div class="col-md-12">
        <ul class="list-group">
            <a 
            class="list-group-item"
            routerLinkActive="active"
            style="cursor: pointer;"
            [routerLink]="[id[i]]"
            *ngFor="let l of list; let i = index" >
                {{ l }}
            </a>
        </ul>
        
    </div>

the component.ts for this list looks like this:

@Input() list: string[] = [];
  @Input() urls: string[] = [];
  @Output() btnpress = new EventEmitter<string>();

  id: string[] = [];

  constructIdList() {
    this.urls.forEach(url => {
      if(url.length > 0) {}
      let tmp = url.split('/');
      if(tmp.length > 0) {
        console.log(tmp.pop());
      }
    });
  }

Adding a method should do the trick:

TS

getRoute(ndx: number): string {
    return "[" + id[ndx] + "]";
}

HTML

[routerLink]="getRoute(i)"

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