简体   繁体   English

亲子组件沟通

[英]Parent-Child Component communication

Which is good below mentioned method for changing the child component properties from parent component? 下文提到的从父组件更改子组件属性的方法中哪一种是好的?

Task: 任务:

I want to add class 'md-show' to my pop up modal component from parent component when parent component loaded 我想在加载父组件时将类'md-show'从父组件添加到弹出模式组件中

@viewchild decorator

or 要么

document.querySelector()

If you have just one component inside popup component. 如果你只有一个component弹出组件内。 You can use the function ngAfterViewInit inside popup component. 您可以在弹出组件内部使用函数ngAfterViewInit Very simple :) 很简单 :)

A better approach than using @ViewChild would be: 比使用@ViewChild更好的方法是:

  1. Define a shouldAddClass property in your ChildComponent and decorate it with an @Input decorator. 在您的ChildComponent中定义一个shouldAddClass属性,并使用@Input装饰器@Input装饰。
  2. Use [ngClass] or [class.md-show] in your ChildComponent Template to add the class to your HTML Element depending on the value of shouldAddClass 在ChildComponent模板中使用[ngClass][class.md-show]将类添加到HTML元素中,具体取决于shouldAddClass的值
  3. In your ParentComponent, create a property named wasParentLoaded of type boolean and set it to false initially. 在您的ParentComponent中,创建一个名为wasParentLoaded的属性,其类型为boolean,并将其初始设置为false
  4. In your ParentComponent template, use the bind wasParentLoaded with the ChildComponent's shouldAddClass @Input property via Property Binding Syntax. 在您的ParentComponent模板中,通过属性绑定语法将绑定wasParentLoaded与ChildComponent的shouldAddClass @Input属性一起使用。
  5. When the Parent Component is Loaded, it's AfterViewInit lifecycle hook will get triggered. 当父组件被加载时,它将触发AfterViewInit生命周期挂钩。 So inside ngAfterViewInit of the ParentComponent, you can simply change wasParentLoaded to true . 因此,在ParentComponent的ngAfterViewInit内部,您可以简单地将wasParentLoaded更改为true

This should do the trick. 这应该可以解决问题。

Here's a Sample StackBlitz for your ref. 这是供您参考的示例StackBlitz

PS: This would give you the ExpressionChangedAfterItHasBeenCheckedError on the console since we're trying to change a property on the Component while Angular was performing its Change Detection. PS:这将在控制台上给您ExpressionChangedAfterItHasBeenCheckedError ,因为我们试图在Angular执行其更改检测时更改Component的属性。 Only in the Development Mode though. 但是仅在开发模式下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM