如何检测角度路由以设置变量?

时间:2019-07-08 12:20:18

标签: angular angular6

我有一个父组件,如下面简化的代码所示。我想在路由到“我的时间表”时设置变量“ showButton”,并在路由到其他路由时将其隐藏。我不知道该怎么做,因为我是新手。 有什么帮助吗? PS:路由工作正常

父组件html:

  <div class="myt-left">
        <div class="row">
           <div class="col-sm text-right ">
        <span *ngIf="
        timesheetStatus.edit
          " class="myt-unselected-tab" routerLink="my-timesheet" 
       routerLinkActive="myt-selected">
      {{ t.my_timesheet }}
       </span>
            <span *ngIf="
  timesheetStatus.review
    " class="myt-unselected-tab" routerLink="timesheet" routerLinkActive="myt-selected">
      {{ t.timesheet }}
    </span>
  </div>
  <div class="col-sm text-center">
    <span class="myt-unselected-tab" routerLink="attached-files" routerLinkActive="myt-selected">
      {{ t.attachments }}
    </span>
  </div>
  <div class="col-sm ">
    <span class="myt-unselected-tab" routerLink="comment" [routerLinkActive]="'myt-selected'">
      {{ t.comments }} ({{ commentsNumber }})
    </span>
  </div>
</div>
<hr class="myt-line" />
<br />

<!------  show this button when routing to my-timesheet------>
<button *ngIf="showButton">Sauvegarder</button>

 <div>
    <router-outlet></router-outlet>
  </div>
 </div>

2 个答案:

答案 0 :(得分:1)

您可以从ActivatedRoute api获取它。它具有可与所需路线进行比较的网址,然后可以相应地显示/隐藏。

  

https://angular.io/api/router/ActivatedRoute#description

答案 1 :(得分:1)

在此处的Paren Component.ts中尝试

function addTable() {
    var abc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    var YWert_len = 5;
    var XWert_len = abc.length;
    var myTableDiv = document.getElementById("tbl");
    var table = document.createElement('TABLE');
    table.border = '1';
    var tableBody = document.createElement('TBODY');
    table.appendChild(tableBody);


    for (var i = 0; i <= YWert_len; i++) {
        var tr = document.createElement('TR');
        tableBody.appendChild(tr);


        for (var j = 0; j < XWert_len; j++) {
            var td = document.createElement('TD');
            td.width = '75';
            if(i==0)
            {
                td.appendChild(document.createTextNode(abc[j]));
            }
            else
            {
                var button = document.createElement("button");
                button.innerHTML = "Button"+i+j;
                td.appendChild(button);
            }
            tr.appendChild(td);
        }
    }

    myTableDiv.appendChild(table);
}
```

然后在ParentComponent html中

import { Router, NavigationEnd } from '@angular/router';
export class ParentCompontent {
constructor(public router: Router) {

this.router.events.subscribe(events => {
  if (events instanceof NavigationEnd) {
    this.active = router.url;
  }
}); 
}