【问题标题】:Disable router navigate link based on conditions根据条件禁用路由器导航链接
【发布时间】:2018-05-11 07:22:34
【问题描述】:

如何根据状态禁用router.navigate 或链接?

如果状态为“否”,那么我不能键入链接来编辑材料?

HTML

<button type="button" (click)="onEditMaterial(material.id)">Edit </button>

TS

onEditMaterial(material_id) {
  this.router.navigate(['materials', material_id, 'edit']);
}

【问题讨论】:

标签: angular angular-routing angular-services angular-router angular-route-guards


【解决方案1】:

&lt;button [attr.disable]="status === 'No'"&gt;click me&lt;/button&gt; .status 是角度组件中的字符串。 &lt;button [disable]="status === 'No'"&gt;click me&lt;/button&gt; 语法。

编辑:disable 属性是用于&lt;input&gt; , &lt;button&gt; 等的 HTML5 属性。您可以使用一些 css 使其看起来更好,以获得更好的用户体验,例如:button:disabled {cursor: not-allowed;}

编辑:另一种方式是这样的

onEditMaterial(material_id) {
    if (this.status === 'No') return; // if the status is 'No' don't do anything

    this.router.navigate(['materials', material_id, 'edit']);
  }

【讨论】:

  • 我的问题,如果 api 已经给出了状态?如何申报?
  • 在组件public status: string = '' 中有一个status 属性。然后在您执行this.http.get(...).toPromise().then((data)=&gt;{//check here the status of the response and change the state of the status to this.status = some_value) 之后 - 您可以通过您正在谈论的服务的代码
  • 你能这样吗?
  • 确定..如果 mat_status 是更改的属性
  • 但是为什么如果我的 mat_status 是 yes,按钮总是被禁用??
【解决方案2】:

要禁用该按钮,您可以按照 DrNio 提供的答案进行操作。 根据评论中的对话,如果您还想在浏览器中更改 URL 时阻止导航,那么您需要使用Router Guard。在此处查看 AuthGuard 的示例:https://angular.io/guide/router#component-less-route-grouping-routes-without-a-component。搜索export class AuthGuard implements CanActivate。你基本上需要实现canActivate方法。

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 2020-10-27
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多