【问题标题】:Angular 7 - Access dynamic property of child from parent componentAngular 7 - 从父组件访问子组件的动态属性
【发布时间】:2019-06-15 09:10:28
【问题描述】:

所以我最近才开始进行 Angular 开发,但我完全缺少一些东西。我有一个使用app.component.html 设置的基本应用程序,如下所示:

<h1>{{ routeTitle }}</h1>
<router-outlet></router-outlet>

app.component.ts 设置为:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  @Input() routeTitle;
}

然后我设置了 2 个其他基本组件,只是为了表明我的路由有效(它们确实如此),但例如在 dashboard.component.ts 上,我似乎无法从它(作为子组件)传递 routeTitle直到父(app.component)显示在H1标签中:

import { Component, OnInit, Output } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
  @Output() routeTitle;

  constructor() { }

  ngOnInit() {
    if (...somelogic...) {
      this.routeTitle = 'Dashboard';
    }
    else {
      this.routeTitle = 'Dashboard (Courier)';
    }
  }
}

请帮忙,因为这让我发疯了,为什么我似乎无法理解一些不应该花这么长时间才能弄清楚的事情。谢谢!

【问题讨论】:

  • 查看this,了解使用@Output()的正确方法。
  • 如果它是动态属性,那么您可以在您的父级中使用订阅该属性。您可以使用主题来做到这一点。

标签: angular angular-routing pass-data


【解决方案1】:

“孩子”这个词用的地方太多,可能有点混乱。

这段代码:

<h1>{{ routeTitle }}</h1>
<router-outlet></router-outlet>

定义子路线

input 属性不适用于子路由

要使用input 属性,您需要将组件定义为子组件 ...所以像这样:

<h1>{{ routeTitle }}</h1>
<my-child-component [myInputProperty]="myTitle"></my-child-component>

其中子组件定义如下:

@Component({
  selector: 'my-child-component',
  templateUrl: './myChild.component.html'
})
export class MyChildComponent {
  @Input() myInputProperty;
  // ...
}

我会假设您真正想做的是在路由之间传递数据?如果是这样,您根本不想使用 input/output 属性。相反,您希望使用多种技术中的一种在路由之间传递数据。

加上 Angular v7.2,他们只是添加了另一种技术:https://netbasal.com/set-state-object-when-navigating-in-angular-7-2-b87c5b977bb

【讨论】:

  • 感谢 Deboarh 的深入解释!我最终阅读了 Angular Services 并使用BehaviorSubject&lt;T&gt; 实现了一个解决方案。我稍后会在下面发布我的最终解决方案
【解决方案2】:

有几种情况我们需要在组件之间传递数据:

  1. 如果你想将一些数据从孩子传递给父母,那么你应该使用@Output。

  2. 有时我们需要在兄弟组件之间传递数据,在那里我们可以使用共享服务并利用 Behavior subject 来传递数据。

    现在有了 Angular7.2,你可以使用state feature

你也可以关注article

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2017-05-20
    • 2014-04-05
    • 2023-03-27
    相关资源
    最近更新 更多