【问题标题】:How to pass data to child component which is routed from parent component?如何将数据传递给从父组件路由的子组件?
【发布时间】:2018-10-01 14:52:32
【问题描述】:

我正在使用父组件的 HTML 模板中的按钮路由到子组件。如何将父组件的数据(比如名称)传递给子组件? 我不想在 URL 中显示数据(如果在 [routerLink] 中传递则显示 - 导航到子组件)

【问题讨论】:

    标签: angular typescript angular-ui-router


    【解决方案1】:

    我从您的问题中了解到,您希望将数据从父路由发送到子路由,而不显示实际 URL,并且不使用路由器链接来避免显示实际链接。如果是这样,您可以设计如下:-

    在您的 html 中,您可以使用 bootstrap4 使用链接类型按钮,您需要添加 onclick 功能,如下所示:-

    <button type="button" class="btn btn-link" (click)="gotochildroute()" >Link</button>
    

    gotochildroute()方法中,使用路由如下:-

    this.route.navigate(['childroute'], {skipLocationChange: true}); 
    

    如果您使用的是链接,那么您可以 skipLocationChange 如下:-

    <a [routerLink]="['/childroute'}]" replaceUrl="false" skipLocationChange="true"> </a>
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      尝试通过服务共享状态。

      创建服务:

      @Injectable()
      export class SomeService {
        data: string;
      }
      

      然后您可以将它包含在源组件和目标组件中。

      @Component({
         ...
      })
      export class SourceComponent {
        constructor(private service: SomeService) {}
      
        onSomeAction() {
          service.data = "Some Data";
          // Route to your component.
        }
      }
      

      然后像这样消费它:

      @Component({
        ...
      })
      export class TargetComponent {
        data: string;
        constructor(private service: SomeService) {} 
      
        ngOnInit() {
          this.data = this.service.data;
        }
      }
      

      您还需要将SomeService 添加到托管模块:

      @NgModule({
        imports:      [ ... ],
        providers:    [ SomeService ],
        declarations: [ SourceComponent, TargetComponent ]
      })
      

      对于更复杂的事情,您可以查看像 https://ngxs.gitbook.io/ngxs 这样的包,它提供了几个强大的功能来处理 Angular 中的状态管理。

      【讨论】:

        【解决方案3】:

        如果您的子组件在您的父组件内,您可以将数据作为输入参数传递。 看这里:https://angular.io/api/core/Input

        在你的父组件中,像这样设置你想要传递给子组件的数据:

        <child-component [inputdata]="yourDataObject">
        

        其中“inputdata”是您可以选择的名称,“yourDataObject”是您要传递给子组件的属性。 在您的子组件中,您可以像这样检索数据:

        @Input('inputdata') passedData;
        

        当然,名称必须与在您的父组件中传递的名称相同。

        【讨论】:

          猜你喜欢
          • 2016-08-28
          • 1970-01-01
          • 2016-09-05
          • 2021-09-12
          • 2019-10-05
          • 2019-01-13
          • 2020-11-01
          • 2019-06-20
          • 2020-05-27
          相关资源
          最近更新 更多